File Handling in Java
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:
The File class has many useful methods for creating and getting information about files.
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().
printStackTrace(PrintStream s)
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:
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.
Java FileWriter and FileReader classes are used to write and read data from text files (they are Character Stream
classes).
FileWriter
FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a
FileOutputStream.
Constructors:
FileWriter (File file, boolean append) – constructs a FileWriter object given a File object.
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 (char [] stir) throws IOException – Writes an array of characters.
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 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.
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(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 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
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
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.
The InputStream is used to read data from a source and the OutputStream is used for writing data to a
destination.
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.
or
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.
or