[go: up one dir, main page]

0% found this document useful (0 votes)
9 views38 pages

File1

The document provides an overview of file handling in Java, detailing the use of the java.io package for input and output operations. It explains how to read from and write to files using InputStream and OutputStream classes, along with examples of reading console input and writing to files. Additionally, it covers directory creation and navigation, as well as a list of Java programs related to file handling.

Uploaded by

Ashok Garg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views38 pages

File1

The document provides an overview of file handling in Java, detailing the use of the java.io package for input and output operations. It explains how to read from and write to files using InputStream and OutputStream classes, along with examples of reading console input and writing to files. Additionally, it covers directory creation and navigation, as well as a list of Java programs related to file handling.

Uploaded by

Ashok Garg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

File Handling

https://sites.google.com/a/tges.org/computer-education/home/isc-10th/file-handling
File Handling

The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All
these streams represent an input source and an output destination. The stream in the java.io package supports many
data such as primitives, Object, localized characters etc.

A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the
OutputStream is used for writing data to a destination.

Java does provide strong, flexible support for I/O as it relates to files and networks but this tutorial covers very basic
functionlity related to streams and I/O. We would see most commonly used example one by one:

Reading Console Input:

Java input console is accomplished by reading from System.in. To obtain a character-based stream that is attached to
the console, you wrap System.in in aBufferedReader object, to create a character stream. Here is most common
syntax to obtain BufferedReader:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

Once BufferedReader is obtained, we can use read( ) method to reach a character or readLine( ) method to read a
string from the console.

Reading Characters from Console:

To read a character from a BufferedReader, we would read( ) method whose sytax is as follows:

int read( ) throws IOException

Each time that read( ) is called, it reads a character from the input stream and returns it as an integer value. It
returns .1 when the end of the stream is encountered. As you can see, it can throw an IOException.

The following program demonstrates read( ) by reading characters from the console until the user types a "q":

// Use a BufferedReader to read characters from the console.

import java.io.*;

class BRRead
{
public static void main(String args[]) throws IOException
{
char c;
// Create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do
{
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}
Here is a sample run:

Enter characters, 'q' to quit.


123abcq
1
2
3
a
b
c
q
Reading Strings from Console:

To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader class. Its
general form is shown here:

String readLine( ) throws IOException

The following program demonstrates BufferedReader and the readLine( ) method. The program reads and displays
lines of text until you enter the word "end":

// Read a string from console using a BufferedReader.


import java.io.*;
class BRReadLines {
public static void main(String args[]) throws IOException
{
// Create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'end' to quit.");
do
{
str = br.readLine();
System.out.println(str);
} while(!str.equals("end"));
}
}

Here is a sample run:

Enter lines of text.


Enter 'end' to quit.
This is line one
This is line one
This is line two
This is line two
end
end
Writing Console Output:

Console output is most easily accomplished with print( ) and println( ), described earlier. These methods are
defined by the class PrintStream which is the type of the object referenced by System.out. Even though System.out
is a byte stream, using it for simple program output is still acceptable.

Because PrintStream is an output stream derived from OutputStream, it also implements the low-level method
write( ). Thus, write( ) can be used to write to the console. The simplest form of write( ) defined by PrintStream is
shown here:

void write(int byteval)

This method writes to the stream the byte specified by byteval. Although byteval is declared as an integer, only the
low-order eight bits are written.

Example:
Here is a short example that uses write( ) to output the character "A" followed by a newline to the screen:

import java.io.*;

// Demonstrate System.out.write().
class WriteDemo
{
public static void main(String args[])
{
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}

This would produce simply 'A' character on the output screen.

Note: You will not often use write( ) to perform console output because print( ) and println( ) are substantially easier
to use.

Reading and Writing Files:

As described earlier, A stream can be defined as a sequence of data. The InputStream is used to read data from a
source and the OutputStream is used for writing data to a destination.

Here is a hierarchy of classes to deal with Input and Output streams.


The two important streams are FileInputStream and FileOutputStream which would be discussed in this tutorial:

FileInputStream:

This stream is used for reading data from the files. Objects can be created using the keyword new and there are
several types of constructors available.

Following constructor takes a file name as a string to create an input stream object to read the file.:

InputStream f = new FileInputStream("C:/java/hello");

Following constructor takes a file object to create an input stream object to read the file. First we create a file object
using File() method as follows:

File f = new File("C:/java/hello");


InputStream f = new FileInputStream(f);

Once you have InputStream object in hand then there is a list of helper methods which can be used to read to stream
or to do other operations on the stream.

SN Methods with Description

1 public void close() throws IOException{}


This method closes the file output stream. Releases any system resources associated with the file. Throws an
IOException.

2 protected void finalize()throws IOException {}


This method cleans up the connection to the file. Ensures that the close method of this file output stream is
called when there are no more references to this stream. Throws an IOException.

3 public int read(int r)throws IOException{}


This method reads the specified byte of data from the InputStream. Returns an int. Returns the next byte of
data and -1 will be returned if it's end of file.
4 public int read(byte[] r) throws IOException{}
This method reads r.length bytes from the input stream into an array. Returns the total number of bytes read.
If end of file -1 will be returned.

5 public int available() throws IOException{}


Gives the number of bytes that can be read from this file input stream. Returns an int.

There are other important input streams available, for more detail you can refer to the following links:
 ByteArrayInputStream
 DataInputStream

FileOutputStream:

FileOutputStream is used to create a file and write data into it.The stream would create a file, if it doesn't already
exist, before opening it for output.

Here are two constructors which can be used to create a FileOutputStream object.

Following constructor takes a file name as a string to create an input stream object to write the file.:

OutputStream f = new FileOutputStream("C:/java/hello")

Following constructor takes a file object to create an output stream object to write the file. First we create a file
object using File() method as follows:

File f = new File("C:/java/hello");


OutputStream f = new FileOutputStream(f);

Once you have OutputStream object in hand then there is a list of helper methods which can be used to write to
stream or to do other operations on the stream.

SN Methods with Description

1 public void close() throws IOException{}


This method closes the file output stream. Releases any system resources associated with the file. Throws an
IOException.

2 protected void finalize()throws IOException {}


This method cleans up the connection to the file. Ensures that the close method of this file output stream is
called when there are no more references to this stream. Throws an IOException.

3 public void write(int w)throws IOException{}


This methods writes the specified byte to the output stream.

4 public void write(byte[] w)


Writes w.length bytes from the mentioned byte array to the OutputStream.

There are other important output streams available, for more detail you can refer to the following links:
 ByteArrayOutputStream
 DataOutputStream

Example:

Following is the example to demonstrate InputStream and OutputStream:


import java.io.*;

public class fileStreamTest


{
public static void main(String args[])
{
try
{
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("C:/test.txt");
for(int x=0; x < bWrite.length ; x++){
os.write( bWrite[x] ); // writes the bytes
}
os.close();

InputStream is = new FileInputStream("C:/test.txt");


int size = is.available();

for(int i=0; i< size; i++)


{
System.out.print((char)is.read() + " ");
}
is.close();
}catch(IOException e)
{
System.out.print("Exception");
}
}
}

The above code would create file test.txt and would write given numbers in binary format. Same would be output on
the stdout screen.

File Navigation and I/O:

There are several other classes that we would be going through to get to know the basics of File Navigation and I/O.
 File Class
 FileReader Class
 FileWriter Class

Directories in Java:

Creating Directories:

There are two useful File utility methods which can be used to create directories:

 The mkdir( ) method creates a directory, returning true on success and false on failure. Failure indicates that
the path specified in the File object already exists, or that the directory cannot be created because the entire
path does not exist yet.
 The mkdirs() method creates both a directory and all the parents of the directory.

Following example creates "/tmp/user/java/bin" directory:

import java.io.File;

class CreateDir
{
public static void main(String args[])
{
String dirname = "/tmp/user/java/bin";
File d = new File(dirname);
// Create directory now.
d.mkdirs();
}
}

Compile and execute above code to create "/tmp/user/java/bin".

Note: Java automatically takes care of path separators on UNIX and Windows as per conventions. If you use a
forward slash (/) on a Windows version of Java, the path will still resolve correctly.

Reading Directories:

A directory is a File that contains a list of other files and directories. When you create a File object and it is a
directory, the isDirectory( ) method will return true.

You can call list( ) on that object to extract the list of other files and directories inside. The program shown here
illustrates how to use list( ) to examine the contents of a directory:

import java.io.File;

class DirList
{
public static void main(String args[])
{
String dirname = "/java";
File f1 = new File(dirname);
if (f1.isDirectory())
{
System.out.println( "Directory of " + dirname);
String s[] = f1.list();
for (int i=0; i < s.length; i++)
{
File f = new File(dirname + "/" + s[i]);
if (f.isDirectory())
{
System.out.println(s[i] + " is a directory");
}
else
{
System.out.println(s[i] + " is a file");
}
}
}
else
{
System.out.println(dirname + " is not a directory");
}
}
}

This would produce following result:


Directory of /mysql
bin is a directory
lib is a directory
demo is a directory
test.txt is a file
README is a file
index.html is a file
include is a directory
Programs

https://www.includehelp.com/java-programs/file-handling-programs.aspx
List of Java File Handling Programs
Program
Qno
1 Java program to create a new file

2 Java program to write content into file using FileOutputStream

3 Java program to read content from file using FileInputStream

4 Java program to write content into file using BufferedWriter

5 Java program to read content from file using BufferedReader

6 Java program to get file size and file path

7 Java program to delete a file

8 Java program to copy files

9 Java program to get the last modification date and time of a file

10 Java program to append text/string in a file

11 Java program to determine number of bytes written to file using DataOutputStream

12 Java program to read text from file from a specified index or skipping byte using FileInputStream

13 Java program to check whether a file is hidden or not

14 Java program to get the size of given file in bytes, kilobytes and megabytes

15 Java program to create directory/folder in particular drive

16 Java program to check whether a file can be read or not

17 Java program to read and print all files from a zip file

18 Java program to get the attributes of a file

19 Java program to get the basic file attributes (specific to DOS)

20 Java program to get the file's owner name

21 Java program to get file creation, last access and last modification time

22 Java program to read content from one file and write it into another file

23 Java program to read a file line by line

24 Java program to traverse all files of a directory/folder

25 Java - Print File Content, Display File using Java Program

26 Java - Copy Content of One File to Another File using Java Program

27 Java program to rename an existing file


Q1 Java program to create a new file

File class is used for file related operations, in this program we will use createNewFile() method of File class
that will return boolean value, if file is created successfully, method will retutn true otherwise it will return
false.

Create New File using Java Program

// Java program to create new file

import java.io.File;

public class CreateFile


{
public static void main(String args[])
{
final String fileName = "file1.txt";

try
{
File objFile = new File(fileName);
if (objFile.createNewFile())
{
System.out.println("File created successfully.");
}
else
{
System.out.println("File creation failed!!!");
}
} catch (Exception Ex)
{
System.out.println("Exception : " + Ex.toString());
}
}
}

Output:

File created successfully.

Q2
Java program to write content into file using
FileOutputStream
This program will write the content into the file using FileOutputStream class. In this
program we are using FileOutputStream.write() method which writes the value in
bytes, so we have to convert String data into bytes.

 String.getBytes() - returns the bytes array.


 FileOutputStream.flush() - Is used to clear the output steam buffer.
 FileOutputStream.close() - Is used to close output stream (Close the file).

Write Content into File using FileOutputStream in Java


// Java program to write content into file
// using FileOutputStream.

import java.io.File;
import java.io.FileOutputStream;
import java.util.Scanner;

public class WriteFile


{
public static void main(String args[])
{
final String fileName = "file1.txt";
try
{
File objFile = new File(fileName);
if (objFile.exists() == false)
{
if (objFile.createNewFile())
{
System.out.println("File created successfully.");
}
else
{
System.out.println("File creation failed!!!");
System.exit(0);
}
}

//writting data into file


String text;
Scanner SC = new Scanner(System.in);

System.out.println("Enter text to write into file: ");


text = SC.nextLine();

//object of FileOutputStream
FileOutputStream fileOut = new FileOutputStream(objFile);
//convert text into Byte and write into file
fileOut.write(text.getBytes());
fileOut.flush();
fileOut.close();
System.out.println("File saved.");
} catch (Exception Ex)
{
System.out.println("Exception : " + Ex.toString());
}
}
}

Output:

Enter text to write into file:


Java is a platform independent language.
File saved.
Q3
Java program to read content from file using
FileInputStream
This program will read the content of the file using FileInputStream
class. FileInputStream class provide the methods for file input related operations.
This program is using FileInputStream.read() method which returns an integer value
and them we are converting it into character. We will read values until -1 is not found.
This is an example of File Handling in Java.

Read Content from File using FileInputStream in Java


// Java program to read content from file
// using FileInputStream

import java.io.File;
import java.io.FileInputStream;

public class ReadFile


{
public static void main(String args[])
{
final String fileName = "file1.txt";
try
{
File objFile = new File(fileName);
if (objFile.exists() == false)
{
System.out.println("File does not exist!!!");
System.exit(0);
}

//reading content from file


String text;
int val;

//object of FileOutputStream
FileInputStream fileIn = new FileInputStream(objFile);
//read text from file
System.out.println("Content of the file is: ");
while ((val = fileIn.read()) != -1)
{
System.out.print((char) val);
}

System.out.println();

fileIn.close();
} catch (Exception Ex)
{
System.out.println("Exception : " + Ex.toString());
}
}
}

Output
Content of the file is:
Java is a platform independent language.

Q4
Java program to write content into file using
BufferedWriter
This program will write the content (string data) into the file
using BufferedWriter class. We will create a file named "file2.txt" in the same
directory.

BufferWriter takes the FileWriter type argument and FileWriter class defines that
file. So we have to create mainly three object:

 A File object to define the filename.


 A FileWriter object to define the File using File Object.
 A BufferedWriter objcet with respect of FileWriter object.

BufferedWriter.write() - This method is used to write String data into the file.

BufferedWriter.close() - This method is used to save and close the file.

Program will read content from the file line by line until null is not found.

Write Content into File using BufferedWriter in Java


// Java program to write content into file
// using BufferedWriter

import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.util.Scanner;

public class ExBufferedWriter


{
public static void main(String args[])
{
final String fileName = "file2.txt";
try
{
File objFile = new File(fileName);
if (objFile.exists() == false)
{
if (objFile.createNewFile())
{
System.out.println("File created successfully.");
}
else
{
System.out.println("File creation failed!!!");
System.exit(0);
}
}

//writting data into file


String text;
Scanner SC = new Scanner(System.in);

System.out.println("Enter text to write into file: ");


text = SC.nextLine();

//instance of FileWriter
FileWriter objFileWriter = new FileWriter(objFile.getAbsoluteFile());
//instnace (object) of BufferedReader with respect of FileWriter
BufferedWriter objBW = new BufferedWriter(objFileWriter);
//write into file
objBW.write(text);
objBW.close();

System.out.println("File saved.");
} catch (Exception Ex)
{
System.out.println("Exception : " + Ex.toString());
}
}
}

Output:

File created successfully.


Enter text to write into file:
Computer is an Electronic Device.
File saved.

Q5
Java program to write content into file using
BufferedWriter
This program will write the content (string data) into the file
using BufferedWriter class. We will create a file named "file2.txt" in the same
directory.

BufferWriter takes the FileWriter type argument and FileWriter class defines that
file. So we have to create mainly three object:

 A File object to define the filename.


 A FileWriter object to define the File using File Object.
 A BufferedWriter objcet with respect of FileWriter object.

BufferedWriter.write() - This method is used to write String data into the file.

BufferedWriter.close() - This method is used to save and close the file.

Program will read content from the file line by line until null is not found.

Write Content into File using BufferedWriter in Java


// Java program to write content into file
// using BufferedWriter

import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.util.Scanner;

public class ExBufferedWriter


{
public static void main(String args[])
{
final String fileName = "file2.txt";
try
{
File objFile = new File(fileName);
if (objFile.exists() == false)
{
if (objFile.createNewFile())
{
System.out.println("File created successfully.");
} else {
System.out.println("File creation failed!!!");
System.exit(0);
}
}

//writting data into file


String text;
Scanner SC = new Scanner(System.in);

System.out.println("Enter text to write into file: ");


text = SC.nextLine();

//instance of FileWriter
FileWriter objFileWriter = new FileWriter(objFile.getAbsoluteFile());
//instnace (object) of BufferedReader with respect of FileWriter
BufferedWriter objBW = new BufferedWriter(objFileWriter);
//write into file
objBW.write(text);
objBW.close();

System.out.println("File saved.");
} catch (Exception Ex) {
System.out.println("Exception : " + Ex.toString());
}
}
}

Output:

File created successfully.


Enter text to write into file:
Computer is an Electronic Device.
File saved.

Q6
Java program to get file size and file path
This program will print the exact (absolute) path of the file and file length i.e. file size in
bytes, to get the file path we will use the File.getAbsolutePath() method and to get
file length (size) we will use File.length() Method.

File.getAbsolutePath() - Method return absolute path of the file, this is the method
of File class.

File.length() - Method returns the file size (length) in the bytes, this is also method of
File class.

Get File Length (Size) and File Path in Java


// Java program to get file size
// and file path

import java.io.File;

public class GetFilePathAndSize {


public static void main(String args[]) {
final String fileName = "file1.txt";
try {
//File Object
File objFile = new File(fileName);

//getting file path


System.out.println("File path is: " + objFile.getAbsolutePath());
//getting filesize
System.out.println("File size is: " + objFile.length() + " bytes.");
} catch (Exception Ex) {
System.out.println("Exception: " + Ex.toString());
}

}
}

Output:

File path is: d:/programs/file1.txt


File size is: 40 bytes.

Q7
Java program to delete a file
This program will delete an existing file. There is a method delete() of File class
which is used to delete the file and returns true or false, if the file deletes method
returns true otherwise false.

In this program. Firstly we are checking file exists or not using


the File.exists() method, if the file exits program will move to the file delete code and
the file will be deleted using File.delete().

Delete File using Java Program


// Java program to get file size
// and file path

import java.io.File;
public class ExDeleteFile {
public static void main(String args[]) {
final String fileName = "file3.txt";

//File class object


File objFile = new File(fileName);

//check file is exist or not, if exist delete it


if (objFile.exists() == true) {
//file exists
//deleting the file
if (objFile.delete()) {
System.out.println(objFile.getName() + " deleted successfully.");
} else {
System.out.println("File deletion failed!!!");
}
} else {
System.out.println("File does not exist!!!");
}
}
}

Output:

file3.txt deleted successfully.

Q8
Java program to copy files
This program will copy files in Java.

Copy Files using Java Program


// Java program to copy file

import java.io.*;

public class FileCopy {


public static void main(String args[]) {
try {
//input file
FileInputStream sourceFile = new FileInputStream(args[0]);
//output file
FileOutputStream targetFile = new FileOutputStream(args[1]);

// Copy each byte from the input to output


int byteValue;
//read byte from first file and write it into second line
while ((byteValue = sourceFile.read()) != -1)
targetFile.write(byteValue);

// Close the files!!!


sourceFile.close();
targetFile.close();

System.out.println("File copied successfully");


}
// If something went wrong, report it!
catch (IOException e) {
System.out.println("Exception: " + e.toString());
}
}
}

Output:

Compile: javac FileCopy.java


Run: java FileCopy file1.txt file2.txt

File copied successfully

Q9
Java program to get the last modification date
and time of a file
In this java program, we will learn how to get the file's last modification date and
time? Here, we will give a file name and program will print its last modification date
and time.
Submitted by IncludeHelp, on October 17, 2017

Given a file name and we have to find its last modification date using java
program.

To implement this program, we are using "File" class, and its


method "lastModified()" which returns file’s last modification date and time.

Here, we are passing (giving) a file named "IncludeHelp.txt' which is stored


in "E:" drive in my system; you can pass any file name with correct path which must be
available in your system.

Consider the program

// This program will display date and time


// of last modification of the file IncludeHelp.txt

import java.io.*;
import java.util.Date;

public class LastModify {


public static void main(String[] args)

{
// Enter the file name here.
File file = new File("E:/IncludeHelp.txt");

// lastModified is the predefined function of date class in java.


long lastModified = file.lastModified();

// will print when the file last modified.


System.out.println("File was last modified at : " + new
Date(lastModified));
}
}

Output

File was last modified at : Sun Oct 15 23:23:34 IST 2017

Q10
Java program to append text/string in a file
In this java program, we are going to learn how to append text/string in a given
file? Here, we have a file with some pre written content and we are appending text in
it.
Submitted by IncludeHelp, on October 19, 2017

Given a file and we have to append text/string in the file using java program.

There is a file named "IncludeHelp.txt" which is stored at my system in "E:" drive


under "JAVA" folder (you can choose your path), and file contains the following text,

This is sample text.

Example:

File's content: "This is sample text."


Text to append: "Text to be appended."
File's content after appending: "This is sample text.Text to be appended."

Consider the program

import java.io.*;

public class AppendFile {


public static void main(String[] args) {
//file name with path
String strFilePath = "E:/JAVA/IncludeHelp.txt";

try {
//file output stream to open and write data
FileOutputStream fos = new FileOutputStream(strFilePath, true);

//string to be appended
String strContent = "Text to be appended.";

//appending text/string
fos.write(strContent.getBytes());

//closing the file


fos.close();
System.out.println("Content Successfully Append into File...");
} catch (FileNotFoundException ex) {
System.out.println("FileNotFoundException : " + ex.toString());
} catch (IOException ioe) {
System.out.println("IOException : " + ioe.toString());
} catch (Exception e) {
System.out.println("Exception: " + e.toString());
}
}
}

Output

Content Successfully Append into File...

Q11
Java program to determine number of bytes
written to file using DataOutputStream
In this java program, we are going to learn how to get (determine) the number of
bytes written to a file using DataOutputStream? Here, we will write text in file
and print the number of written bytes.
Submitted by IncludeHelp, on October 19, 2017

Given a file and we have to write text and print the total number of written
bytes using DataOutputSteam using Java program.

There is a file named "IncludeHelp.txt" which is stored at my system in "E:" drive


under "JAVA" folder (you can choose your path), and in this file we will write some text
and print the total number of written bytes.

Example:

Text to write in file: "IncludeHelp is for computer science students."


Output: Total 45 bytes are written to stream.

First of all we will create an object of FileOutputStream by passing the file’s path and
then we will create an object of DataOutputStream by passing object
of FileOutputStream.

Then, we will write the text into file using writeBytes() method
of DataOutputStream and finally we will get the size of the file by using size() method
of DataOutputStream class.

In this program,

 objFOS is the object of FileOutputStream class


 objDOS is the object of DataOutputStream class

Consider the program

import java.io.*;

public class ExToDetermineWrittenDataSize {


// Java program to determine number of bytes
// written to file using DataOutputStream
public static void main(String[] args) {
try {
FileOutputStream objFOS = new FileOutputStream("E:/includehelp.txt");
DataOutputStream objDOS = new DataOutputStream(objFOS);
objDOS.writeBytes("IncludeHelp is for computer science students.");

int bytesWritten = objDOS.size();


System.out.println("Total " + bytesWritten + " bytes are written to
stream.");

objDOS.close();
} catch (Exception ex) {
System.out.println("Exception: " + ex.toString());
}

}
}

Output

Total 45 bytes are written to stream.

Q12
Java program to read text from file from a
specified index or skipping byte using
FileInputStream
In this program, we are going to learn how to read text from a file after skipping
some bytes and print them on the output screen using FileInputStream.
Submitted by IncludeHelp, on October 19, 2017

Given a file with some text and we have to print text after skipping some
bytes using FileInputStream in Java.

There is a file named "IncludeHelp.txt" which is stored at my system in "E:" drive


under "JAVA" folder (you can choose your path), and file contains the following text,

The quick brown fox jumps over the lazy dog.

Example:

File's content is: "The quick brown fox jumps over the lazy dog."
After skipping starting 10 bytes...
Output: "brown fox jumps over the lazy dog."

Consider the program

import java.io.*;

public class Skip {


public static void main(String[] args) {
//file class object
File file = new File("E:/JAVA/IncludeHelp.txt");

try {
FileInputStream fin = new FileInputStream(file);
int ch;
System.out.println("File's content after 10 bytes is: ");

//skipping 10 bytes to read the file


fin.skip(10);

while ((ch = fin.read()) != -1)


System.out.print((char) ch);
} catch (FileNotFoundException ex) {
System.out.println("FileNotFoundException : " + ex.toString());
} catch (IOException ioe) {
System.out.println("IOException : " + ioe.toString());
} catch (Exception e) {
System.out.println("Exception: " + e.toString());
}
}
}

Output

File's content after 10 bytes is:


brown fox jumps over the lazy dog.

Q13
Java program to check whether a file is hidden
or not
In this java program, we are going to learn, how to check whether a file is hidden
or not? Method isHidden() of "File" class is used to check it.
Submitted by IncludeHelp, on October 27, 2017

Given a file, and we have to check whether it is hidden or not using Java
program?

File.isHidden()
This is a method of "File" class, which returns true if a file has hidden property and
return false if it is not.

In this program, we are using a file named "includehelp.txt" which is stored


in "E:\" in my system, program will check its hidden property and returns the
result.

Program to check file is hidden or not in java


import java.io.*;

public class IsHidden {


public static void main(String[] args) {
// create file object.
File file = new File("E:/includehelp.txt");

// this will check is the file hidden or not.


boolean blnHidden = file.isHidden();

// return result in true or false condition.


System.out.println("Is the file " + file.getPath() + " hidden ?: " +
blnHidden);
}
}

Output

Is the file E:\includehelp.txt hidden ?: false

Here, we are using an another method file.getPath() which returns the file name
with path of that file, which is used while creating an object of “File” class.

Q14
Java program to get the size of give file in bytes,
kilobytes and megabytes
In this Java program, we are going to learn how to get the size of a given file in
bytes, kilobytes and megabytes?
Submitted by IncludeHelp, on October 27, 2017

Given a file and we have to get the file size using Java program.

File.length()
This is a method of "File" class, which returns the file’s length (file size) in bytes.

In this program, we are using a file named "includehelp.txt" which is stored


in "E:\" in my system, program will get its size in bytes and then we will convert file
size in kilobytes and megabytes.

Program to get size of given file in Java


import java.io.*;

public class ReturnFileSize


{
public static void main(String[] args)
{
//create file object.
// enter the file name.
File file = new File("E:/includehelp.txt");

// calculate the size of the file.


long fileSize = file.length();

// return the file size in bytes,KB and MB.


System.out.println("File size in bytes is : " + fileSize);
System.out.println("File size in KB is : " +
(double)fileSize/1024);
System.out.println("File size in MB is : " +
(double)fileSize/(1024*1024));
}
}
Output

File size in bytes is : 41


File size in KB is : 0.0400390625
File size in MB is : 3.910064697265625E-5

Q15
Java program to create directory/folder in
particular drive
In this Java program, we will learn how we can create a directory or a folder? To
create a directory, we use File.mkdir() method in Java.
Submitted by IncludeHelp, on October 27, 2017

File.mkdir()
This is a method of "File" class in Java and used to create a directory at specified path,
it return true if directory creates or returns false if directory does not create.

Here, first of all we are creating an object name dir of "File" class by specifying
the "directory name with the path (drive name)" and then we are
using dir.mkdir() method to create directory (Here, dir is an object of "File" class).

Program to create directory in Java


import java.io.*;

public class CreateDirectory {


public static void main(String[] args) {
//object of File class with file path and name
File dir = new File("E:/IHelp");

//method 'mkdir' to create directroy and result


//is getting stored in 'isDirectoryCreated'
//which will be either 'true' or 'false'
boolean isDirectoryCreated = dir.mkdir();

//displaying results
if (isDirectoryCreated)
System.out.println("Directory successfully created: " + dir);
else
System.out.println("Directory was not created successfully: " + dir);
}
}

Output

Directory successfully created: E:\IHelp

Q16
Java program to check whether a file can be
read or not
In this java program, we are going to check whether a given file can be read or
not? To check this, we are using File.canRead() method.
Submitted by IncludeHelp, on October 28, 2017

Given a file, and we have to check whether file can be read or not using Java
program.

In this program, there is a file named "C.txt" which is saved in "E:\" drive in my
system, so that path is "E:/C.txt".

To check that file can be read or not, there is a method canRead() of "File" class, it
returns 'true' if file can be read or returns 'false' if file cannot be read.

Program to check, file can be read or not in Java


import java.io.*;

public class DetermineFileCanBeRead {


public static void main(String[] args) {
String filePath = "E:/C.txt";
File file = new File(filePath);

if (file.canRead()) {
System.out.println("File " + file.getPath() + " can be read");
} else {
System.out.println("File " + file.getPath() + " can not be read");
}
}
}

Output

File E:\A.txt can be read

Q17
Java program to read and print all files from a zip
file
In this java program, we are going to learn how to read a zip file and access all
files from it? Here, we will have a zip file, read files from it and print file names.
Submitted by IncludeHelp, on November 03, 2017

Given a zip file, and we have to print all files names from it using java
program.

To implement this java program, we are going to use main classes FileInputStream to
manage normal files by creating its object, and ZipInputStream to manage zip files by
creating its object.

There are two other methods of ZipInputStream class, which are:

1. getNextEntry() - this will check whether next file (while calling it in the loop) is
available in the zip file or not.
2. getName() - to get file’s name from the zip file.
Program to extract the names of files from zip file in java
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class FindFileInZipFile {


public void printFileList(String filePath) {
// initializing the objects.
FileInputStream fis = null;
ZipInputStream Zis = null;
ZipEntry zEntry = null;

try {
fis = new FileInputStream(filePath);
Zis = new ZipInputStream(new BufferedInputStream(fis));

// this will search the files while end of the zip.


while ((zEntry = Zis.getNextEntry()) != null) {
System.out.println(zEntry.getName());
}
Zis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//main function
public static void main(String a[]) {
// creating object of the file.
FindFileInZipFile fff = new FindFileInZipFile();
System.out.println("Files in the Zip are : ");

// enter the path of the zip file with name.


fff.printFileList("D:/JAVA.zip");
}
}

Output

Files in the Zip are :


ExOops.java

Q18
Java program to get the attributes of a file
In this java program, we are going to learn how to get and print the attributes of a
file? Here, we are accessing the attributes like file creation time, last access time, last
modified time, file key etc.
Submitted by IncludeHelp, on November 07, 2017

Given a file and we have to find its attributes using java program.
Following packages are using here, to implement this program,

 java.nio.file.*
 java.nio.file.attribute.*

There are following two important classes, which are using this program to get the file
attributes,

 BasicFileAttributeView
 BasicFileAttributes

The method readAttributes() of BasicFileAttributeView is using to get the file


attributes.

Program to get file attributes in java


import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.Scanner;

public class BasicAttributeOfFile {


public static void main(String[] args) throws Exception {
// create object of scanner.
Scanner KB = new Scanner(System.in);

// enter path here.


System.out.print("Enter the file path : ");
String A = KB.next();
Path path = FileSystems.getDefault().getPath(A);

// function is used to view file attribute.


BasicFileAttributeView view = Files.getFileAttributeView(path,
BasicFileAttributeView.class);
BasicFileAttributes attributes = view.readAttributes();

// all the attributes of the file.


System.out.println("Creation Time: " + attributes.creationTime());
System.out.println("Last Accessed Time: " +
attributes.lastAccessTime());
System.out.println("Last Modified Time: " +
attributes.lastModifiedTime());
System.out.println("File Key: " + attributes.fileKey());
System.out.println("Directory: " + attributes.isDirectory());
System.out.println("Other Type of File: " + attributes.isOther());
System.out.println("Regular File: " + attributes.isRegularFile());
System.out.println("Symbolic File: " + attributes.isSymbolicLink());
System.out.println("Size: " + attributes.size());
}
}

Output

Enter the file path : E:/JAVA


Creation Time: 2017-10-10T06:03:22.695314Z
Last Accessed Time: 2017-11-04T06:09:35.778029Z
Last Modified Time: 2017-11-04T06:09:35.778029Z
File Key: null
Directory: true
Other Type of File: false
Regular File: false
Symbolic File: false
Size: 4096

Q19
Java program to get the basic file attributes
(specific to DOS)
In this java program, we are going to learn how to get DOS based basic attributes
like file’s hidden, read-only property etc?
Submitted by IncludeHelp, on November 07, 2017

Given a file and we have to find its attributes using java program.

Following packages are using here, to implement this program,

 java.nio.file.*
 java.nio.file.attribute.*

There are following two important classes, which are using this program to get the DOS
based file attributes

 DosFileAttributeView
 DosFileAttributes

The method readAttributes() of DosFileAttributeView is using to is using to get


the Basic file attributes.

Program to get DOS based basic file attributes in java


import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.Scanner;

public class DosAttributeOfFile {


public static void main(String[] args) throws Exception {
// create object of scanner.
Scanner KB = new Scanner(System.in);

// enter path here.


System.out.print("Enter the file path : ");
String A = KB.next();
Path path = FileSystems.getDefault().getPath(A);

// create object of dos attribute.


DosFileAttributeView view = Files.getFileAttributeView(path,
DosFileAttributeView.class);

// this function read the attribute of dos file.


DosFileAttributes attributes = view.readAttributes();

System.out.println("isArchive: " + attributes.isArchive());


System.out.println("isHidden: " + attributes.isHidden());
System.out.println("isReadOnly: " + attributes.isReadOnly());
System.out.println("isSystem: " + attributes.isSystem());
}
}
Output

First run:
Enter the file path : E:/JAVA
isArchive: false
isHidden: true
isReadOnly: false
isSystem: false

Second run:
Enter the file path : D:/Study
isArchive: false
isHidden: false
isReadOnly: false
isSystem: false

Q20
Java program to get the file's owner name
In this java program, we are going to learn how to get the file's owner name?
Method getOwner() of class FileOwnerAttributeView is used to get the owner
name.
Submitted by IncludeHelp, on November 07, 2017

Given a file and we have to get, print the file's owner name.

Following packages are using here, to implement this program,

 java.nio.file.*
 java.nio.file.attribute.*

There are following two important classes, which are using this program to get the file's
owner name.

 FileOwnerAttributeView
 UserPrincipal

The method getOwner() gives the owner's name to the object of UserPrincipal class,
which can be accessed through getName() method.

Program to get owner's name of a file in java


import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.Scanner;

public class OwnerOfFile {


public static void main(String[] args) throws Exception {
// create object of scanner.
Scanner KB = new Scanner(System.in);

// enter path here.


System.out.print("Enter the file path : ");
String A = KB.next();
Path path = Paths.get(A);

// create object of file attribute.


FileOwnerAttributeView view = Files.getFileAttributeView(path,
FileOwnerAttributeView.class);

// this will get the owner information.


UserPrincipal userPrincipal = view.getOwner();

// print information.
System.out.println("Owner of the file is :" + userPrincipal.getName());
}
}

Output

Enter the file path : E:/JAVA


Owner of the file is : DESKTOP-LP73A9B\INCLUDEHELP

Q21
Java program to get file creation, last access and
last modification time
In this java program, we are going to learn how to access file’s last access time,
creation time and last modified time using BasicFileAttributes class.
Submitted by IncludeHelp, on November 12, 2017

Given a file and we have to access its creation, last access and last modified
time using Java program.

Following packages are using here, to implement this program,

 java.nio.file.*
 java.nio.file.attribute.*
 java.util.Calendar;

Program to get file creation, last access and last


modification time in java
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.Calendar;
import java.util.Scanner;

public class TimeAttributeOfFile {


public static void main(String[] args) throws Exception {
// create object of scanner.
Scanner KB = new Scanner(System.in);

// enter path here.


System.out.print("Enter the file path : ");
String A = KB.next();
Path path = Paths.get(A);
BasicFileAttributeView view = Files.getFileAttributeView(path,
BasicFileAttributeView.class);

BasicFileAttributes attributes = view.readAttributes();

// calculate time of modification and creation.


FileTime lastModifedTime = attributes.lastModifiedTime();
FileTime createTime = attributes.creationTime();

long currentTime = Calendar.getInstance().getTimeInMillis();


FileTime lastAccessTime = FileTime.fromMillis(currentTime);

view.setTimes(lastModifedTime, lastAccessTime, createTime);

System.out.println("Creation time of file is : " +


attributes.creationTime());
System.out.println("Last modification time of file is : " +
attributes.lastModifiedTime());
System.out.println("Last access time of file is : " +
attributes.lastAccessTime());
}
}

Output

Enter the file path : E:/JAVA


Creation time of file is : 2017-10-10T06:03:22.695314Z
Last modification time of file is : 2017-11-04T06:09:35.778029Z
Last access time of file is : 2017-11-04T06:09:35.778029Z

Q22
Java program to read content from one file and
write it into another file
In this java program, we are going to learn how to read content from one file and
write it into another file?
Submitted by IncludeHelp, on November 19, 2017

Given a file and we have to read content from it and write in another file
using java program. This is an example of File Handling in Java.

Program to read content from a file and write in


another in java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class CopyFile {


public static void main(String[] args) {
try {
boolean create = true;
Scanner KB = new Scanner(System.in);

System.out.print("Enter Source File Name:");


String sfilename = KB.next();
File srcfile = new File(sfilename);
if (!srcfile.exists()) {
System.out.println("File Not Found..");
} else {
FileInputStream FI = new FileInputStream(sfilename);
System.out.print("Enter Target File Name:");
String tfilename = KB.next();
File tfile = new File(tfilename);
if (tfile.exists()) {
System.out.print("File Already Exist OverWrite it..Yes/No?:");
String confirm = KB.next();
if (confirm.equalsIgnoreCase("yes")) {
create = true;
} else {
create = false;
}
}
if (create) {
FileOutputStream FO = new FileOutputStream(tfilename);
int b;
//read content and write in another file
while ((b = FI.read()) != -1) {
FO.write(b);
}
System.out.println("\nFile Copied...");
}
FI.close();
}
} catch (IOException e) {
System.out.println(e);
}
}
}

Output

File Copied...

Q23
Java program to read a file line by line
In this java program, we are going to learn how to read a file line by line and print
the line on the output screen? Here, we are reading content of a file line by line and
printing.
Submitted by IncludeHelp, on November 19, 2017

Given a file and we have to read its content line by line using java program.

For this program, I am using a file named "B.txt" which is located at "E:\" drive, hence
the path of the file is "E:\B.txt", and the content of the file is:

This is line 1
This is line 2
This is line 3
This is line 4

Program to read file line by line in java


import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
public class ReadLineByLine {
public static void main(String[] args) {
// create object of scanner class.
Scanner Sc = new Scanner(System.in);

// enter file name.


System.out.print("Enter the file name:");
String sfilename = Sc.next();
Scanner Sc1 = null;
FileInputStream fis = null;
try {
FileInputStream FI = new FileInputStream(sfilename);
Sc1 = new Scanner(FI);

// this will read data till the end of data.


while (Sc1.hasNext()) {
String data = Sc1.nextLine();

// print the data.


System.out.print("The file data is : " + data);
}
} catch (IOException e) {
System.out.println(e);
}
}

Output

Enter the file name: E:/B.txt


This is line 1
This is line 2
This is line 3
This is line 4

Q24
Java program to traverse all files of a
directory/folder
In this java program, we are going to learn how to access and traverse all files of a
directory/folder? Here, we are traversing all files of a given directory.
Submitted by IncludeHelp, on December 05, 2017

Given a directory (folder) and we have to traverse its all files using java
program.

Example:

Input:
Enter path: 'E:\Java'
(Java folder in 'E' drive)

Output:
About to traverse the directory: JAVA
About to traverse the directory: 1 Nov
Visiting file:ChristmasTree.java
Visiting file:Find Files in Zip File.docx
Finished with the directory: 1 Nov
About to traverse the directory: 2 Nov
Visiting file:Combine Path.docx
Visiting file:CombinePath.java
Finished with the directory: 2 Nov
About to traverse the directory: 3 Nov
Visiting file:Check absolute path.docx
Visiting file:CheckAbsolutePath.java
Finished with the directory: 2 Nov

Program to traverse all files from a directory in java


import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Scanner;

public class TraverseFileSystem {


public static void main(String[] args) {
try {
// create object of scanner.
Scanner KB = new Scanner(System.in);

// enter path here.


System.out.print("Enter path here : ");
String A = KB.next();
Path path = Paths.get(A);
ListFiles listFiles = new ListFiles();
Files.walkFileTree(path, listFiles);
} catch (IOException e) {
e.printStackTrace();
}
}
}

class ListFiles extends SimpleFileVisitor < Path > {


private final int indentionAmount = 3;
private int indentionLevel;

public ListFiles() {
indentionLevel = 0;
}

private void indent() {


for (int i = 0; i < indentionLevel; i++) {
System.out.print(' ');
}
}

public FileVisitResult visitFile(Path file, BasicFileAttributes


attributes) {
indent();
System.out.println("Visiting file:" + file.getFileName());
return FileVisitResult.CONTINUE;
}

public FileVisitResult postVisitDirectory(Path directory, IOException e)


throws IOException {
indentionLevel = indentionAmount;
indent();
System.out.println("Finished with the directory: " +
directory.getFileName());
return FileVisitResult.CONTINUE;
}

public FileVisitResult preVisitDirectory(Path directory,


BasicFileAttributes attributes) throws IOException {
indent();
System.out.println("About to traverse the directory: " +
directory.getFileName());
indentionLevel += indentionAmount;
return FileVisitResult.CONTINUE;
}

public FileVisitResult visitFileFailed(Path file, IOException exc) throws


IOException {
System.out.println("A file traversal error ocurred");
return super.visitFileFailed(file, exc);
}
}

Output

Enter path here : E:/JAVA


About to traverse the directory: JAVA
About to traverse the directory: 1 Nov
Visiting file:ChristmasTree.java
Visiting file:Find Files in Zip File.docx
Finished with the directory: 1 Nov
About to traverse the directory: 2 Nov
Visiting file:Combine Path.docx
Visiting file:CombinePath.java
Finished with the directory: 2 Nov
About to traverse the directory: 3 Nov
Visiting file:Check absolute path.docx
Visiting file:CheckAbsolutePath.java
Finished with the directory: 2 Nov

Q25
Java - Print File Content, Display File
In this code snippet, we will print the file size and file content using Java program.

Print/Display File Content


// Java - Print File Content, Display File

import java.io.*;

public class PrintFile {


public static void main(String args[]) throws IOException {
File fileName = new File("d:/sample.txt");

FileInputStream inFile = new FileInputStream("d:/sample.txt");


int fileLength = (int) fileName.length();

byte Bytes[] = new byte[fileLength];

System.out.println("File size is: " + inFile.read(Bytes));


String file1 = new String(Bytes);
System.out.println("File content is:\n" + file1);

//close file
inFile.close();
}
}

Output:

File size is: 22


File content is:
This is a sample file.

Q26
Java - Copy Content of One File to Another File
In this code snippet, we will learn how to copy content of one file to another file using
Java program. In this example we will copy file named "sample.txt" to
"sampleCopy.txt".

Copy Content of One File to Another File


// Java - Copy Content of One File to Another File

import java.io.*;

public class CopyFile {


public static void main(String args[]) throws IOException {
File fileName = new File("d:/sample.txt");

FileInputStream inFile = new FileInputStream("d:/sample.txt");


int fileLength = (int) fileName.length();

byte Bytes[] = new byte[fileLength];

System.out.println("File size is: " + inFile.read(Bytes));

String file1 = new String(Bytes);


System.out.println("File content is:\n" + file1);

FileOutputStream outFile = new FileOutputStream("d:/sample-copy.txt");

for (int i = 0; i < fileLength; i++) {


outFile.write(Bytes[i]);
}

System.out.println("File copied.");
//close files
inFile.close();
outFile.close();
}
}

Output:

File size is: 22


File content is:
This is a sample file.
File copied.

Q27
Java program to rename an existing file
In this Java program, we are going to learn how to rename an existing file? This
task can we performed using 'renameTo()' method, which is a method of 'File'
class.

Given a file and we have to rename the file name.

To rename a file name, we use renameTo() method, which is a method of File class.
Here, we are using statement File F=new File("f:/Includehelp.txt"); to create
an object of File class by passing file name. Here, "Includehelp.txt" is the file name,
which is saved in "f:" drive.

Consider the program:

import java.io.File;
import java.io.IOException;

public class RenameFile {


public static void main(String[] args) {
try
// Here F is the object of the Existing file named
// with Includehelp which is to be renamed
{
File F = new File("f:/Includehelp.txt");

// Here T is the object of the renamed file


// of Includehelp which is Include.txt
File T = new File("f:/Include.txt");

// Rename the file Includehelp.txt


// into Include.txt
F.renameTo(T);

// Print the result if file renamed


System.out.println("File Rename Successfully...");
}
// If any error occurs while renaming the file
catch (Exception e) {
System.out.println(e);
}
}
}

Output

File Rename Successfully...

You might also like