You are on page 1of 6

File Handling in Java

Files:

The File class from the java.io package, allows us to work with files.

To use the File class, create an object of the class, and specify the filename or directory name:

Example:

importjava.io.File; // Import the File class

File myObj = new File("filename.txt"); // Specify the filename

The File class has many useful methods for creating and getting information about files.

Method Type Description


canRead() Boolean Tests whether the file is readable or not
canWrite() Boolean Tests whether the file is writable or not
createNewFile() Boolean Creates an empty file
delete() Boolean Deletes a file
exists() Boolean Tests whether the file exists
getName() String Returns the name of the file
getAbsolutePath() String Returns the absolute pathname of the file
length() Long Returns the size of the file in bytes
list() String[] Returns an array of the files in the directory
mkdir() Boolean Creates a directory

 printStackTrace() method

The printStackTrace() method of Java.lang.Throwable class used to print this Throwable along with other
details like class name and line number where the exception occurred means its backtrace. This method prints a
stack trace for this Throwable object on the standard error output stream.
The first line of output shows the same string which was returned by the toString() method for this object means
Exception class name and later lines represent data previously recorded by the method fillInStackTrace().

Syntax: public void printStackTrace()

Return Value: This method do not returns anything.

 printStackTrace(PrintStream s)

The printStackTrace(PrintStream s) method of Java.lang.Throwable class used to print this Throwable


along with other details like class name and line number where the exception occurred to the specified print
stream. This method works same as printStackTrace() but difference is only that it prints to specified print
stream passed as parameter.

Syntax: public void printStackTrace(PrintStream s)


Parameters: This method accepts PrintStream s as a parameter which is specified print stream where we want
to write this Throwable detail.

Return Value: This method do not returns anything.

 Create a File

Use the createNewFile() method to create a file. This method returns a boolean value: true if the file was
successfully created, and false if the file already exists. Note that the method is enclosed in a try...catch block.
This is necessary because it throws an IOException if an error occurs (if the file cannot be created for some
reason):

To create a file in a specific directory (requires permission), specify the path of the file and use double
backslashes to escape the "\" character (for Windows). On Mac and Linux you can just write the path, like:
/Users/name/filename.txt

Example:

File myObj = newFile("C:\\Users\\MyName\\filename.txt");

 Get File Information

After we have created a file, we can use other File methods to get information about that file:

 Write To a File
In the following example, we use the FileWriter class together with its write() method to write some text to
the file we created. Note that when you are done writing to the file, you should close it with the close()
method:

 Read a File

We use the Scanner class to read the contents of the text file we created in the example above:

Note: There are many available classes in the Java API that can be used to read and write files in Java:
FileReader, BufferedReader, Files, Scanner, FileInputStream, FileWriter, BufferedWriter, FileOutputStream,
etc. Which one to use depends on the Java version you're working with and whether you need to read bytes or
characters, and the size of the file/lines etc.

File handling in Java using FileWriter and FileReader

Java FileWriter and FileReader classes are used to write and read data from text files (they are Character Stream
classes).

 FileWriter

FileWriter is useful to create a file writing characters into it.

 This class inherits from the OutputStreamWriter class.


 The constructors of this class assume that the default character encoding and the default byte-buffer size
are acceptable. To specify these values yourself, construct an OutputStreamWriter on a
FileOutputStream.

 FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a
FileOutputStream.

 FileWriter creates the output file , if it is not present already.

Constructors:

 FileWriter(File file) – Constructs a FileWriter object given a File object.

 FileWriter (File file, boolean append) – constructs a FileWriter object given a File object.

 FileWriter (FileDescriptorfd) – constructs a FileWriter object associated with a file descriptor.

 FileWriter (String fileName) – constructs a FileWriter object given a file name.

 FileWriter (String fileName, Boolean append) – Constructs a FileWriter object given a file name with
a Boolean indicating whether or not to append the data written.

Methods:

 public void write (int c) throws IOException – Writes a single character.

 public void write (char [] stir) throws IOException – Writes an array of characters.

 public void write(String str)throws IOException – Writes a string.

 public void write(String str,intoff,intlen)throws IOException – Writes a portion of a string. Here off
is offset from which to start writing characters and len is number of character to write.

 public void flush() throws IOException - flushes the stream

 public void close() throws IOException- flushes the stream first and then closes the writer

Reading and writing take place character by character, which increases the number of I/O operations and effects
performance of the system. BufferedWriter can be used along with FileWriter to improve speed of execution.

 FileReader

FileReader is useful to read data in the form of characters from a ‘text’ file.

 This class inherits from the InputStreamReader Class.

 The constructors of this class assume that the default character encoding and the default byte-buffer size
are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.
 FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a
FileInputStream.

Constructors:

 FileReader(File file) – Creates a FileReader , given the File to read from

 FileReader(FileDescripterfd) – Creates a new FileReader , given the FileDescripter to read from

 FileReader(String fileName) – Creates a new FileReader , given the name of the file to read from

Methods:

 publicint read () throws IOException – Reads a single character. This method will block until a
character is available, an I/O error occurs, or the end of the stream is reached.

 publicint read(char[] cbuff) throws IOException – Reads characters into an array. This method will
block until some input is available, an I/O error occurs, or the end of the stream is reached.

 public abstract int read(char[] buff, int off, intlen) throws IOException –Reads characters into a
portion of an array. This method will block until some input is available, an I/O error occurs, or the end
of the stream is reached.
Parameters:
cbuf – Destination buffer
off – Offset at which to start storing characters
len – Maximum number of characters to read

 public void close() throws IOException closes the reader.

 public long skip(long n) throws IOException –Skips characters. This method will block until some
characters are available, an I/O error occurs, or the end of the stream is reached.
Parameters:
n – The number of characters to skip

Java File & I/O

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.

 Stream

A stream can be defined as a sequence of data. There are two kinds of Streams

 InPutStream − The InputStream is used to read data from a source.

 OutPutStream − The OutputStream is used for writing data to a destination.


Java provides strong but flexible support for I/O related to files and networks but this tutorial covers very basic
functionality related to streams and I/O.

 Byte Streams

Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to
byte streams but the most frequently used classes are, FileInputStream and FileOutputStream.

 Character Streams

Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character streams are
used to perform input and output for 16-bit unicode. Though there are many classes related to character streams
but the most frequently used classes are, FileReader and FileWriter. Though internally FileReader uses
FileInputStream and FileWriter uses FileOutputStream but here the major difference is that FileReader reads
two bytes at a time and FileWriter writes two bytes at a time.

Reading and Writing Files using FileInputStream and FileOutputStream

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.

 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.

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

or

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

InputStream f = new FileInputStream(f);

 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.

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

or

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

OutputStream f = new FileOutputStream(f);


Class Methods Description
This method closes the file output stream.
public void close() throws Releases any system resources associated with
IOException{} the file. Throws an 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
protected void finalize()throws references to this stream. Throws an
IOException {} IOException.
This method reads the specified byte of data
FileInputStream from the InputStream. Returns an int. Returns
public int read(int r)throws the next byte of data and -1 will be returned if
IOException{} it's the end of the file.
This method reads r.length bytes from the input
stream into an array. Returns the total number of
public int read(byte[] r) throws bytes read. If it is the end of the file, -1 will be
IOException{} returned.
public int available() throws Gives the number of bytes that can be read from
IOException{} this file input stream. Returns an int.
This method closes the file output stream.
public void close() throws Releases any system resources associated with
IOException{} the file. Throws an 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
FileOutputStream protected void finalize()throws references to this stream. Throws an
IOException {} IOException.
public void write(int w)throws This methods writes the specified byte to the
IOException{} output stream.
Writes w.length bytes from the mentioned byte
public void write(byte[] w) array to the OutputStream.

You might also like