file handling in java

File handling in Java is defined as reading and writing data to a file. The particular file class from the package called allows us to handle and work with different formats of files. Thus,  if we want to use a file class, we need to create an object of that particular class and should specify the filename or directory name.


As discussed above, the package that supports stream input/output is, and it is vast. This package defines over seventy classes and interfaces, many of which have a large number of methods. 

  • It will be able to give you a chance to read files from the data.
  • It will give us a chance to create a formatted line for the command.
  • It will give us the chance to read or write basic data.
  • It will give us a chance to read or write files containing objects.

Understanding Streams

The stream is the only representation of input or output that is maybe a source or destination of the data. We can also write the data in the stream or read the particular data from the stream. We can also visualize the stream of data as a sequence of bytes that flow out of the program.

Image result for understanding file streams diagram

Input and Output Streams

Writing data in the stream or to a stream is called an output stream. The particular output stream can go to any device which can connect through a hard disk or maybe any stream which can contain the sequence of bytes. An output stream also can be displayed on any output screen, which has its true capability. Stream output to your display is output to your command line. When you start writing something for your display screen, it can only display the characters but not the graphical content. Graphical output requires more specialized support.

You read data from an input stream. In principle, this can only be any source of serial data but is typically a disk file, the keyboard, or a remote computer.

Further, under normal circumstances, the file input and output you write in a machine can only be through a java application. It’s not available to java apples except strictly to a limited extent. 

This has two advantages: First, you don’t have to worry about the detailed mechanics of each device, which are taken care of behind the scenes. 

The streams which you write under the input and output can only have a small amount of data like a single character, but not more than that. Transferring data to or from a stream like this may be extremely inefficient, so a stream often equipped with a buffer in memory, in which case it is called a buffered stream.

The Classes for Input and Output

The logical structure forms with the number of stream classes. Once you know how they are related, you shouldn’t have much trouble using them. We will work through the class hierarchy from the top down, so you will be able to see how the classes hang together and how you can combine them in different ways to suit different situations. it contains all the classes for the support of the streams.

Input StreamThe base class for byte stream input operations.
Output StreamThe base class for byte stream output operations.

Input Stream and Output Stream are both abstract classes.

Basic Input Stream Operations 

As you saw in the previous statement, the Input Stream class is abstract, so you cannot create objects of this class type.

read()This method is abstract in the Input Stream class, so it has to be defined in a subway. This method returns the next byte available as stream int. Once the stream is getting towards an end, the method gives -1. An exception of type IOException will be thrown if an I/O error occurs. 
read(byte[] array)It reads byte from the successive streams to the array. The maximum of array.length bytes will be read. This method will not return the data until the stream gets to the end. If the method will reach the end then it will not return the end of bytes.
read(byte[] array, int offset, int length)It works the same as the previous methods except the length.

Basic Output Streams Operations 

Independent output stream contains three write methods for writing the data into a stream. As can be expected, these mirrors the read() methods of the Input Stream class. This class is also abstract, so subclasses can be instantiated. The principal direct subclasses of Output Stream are shown.  

  • FileOutputStream – for writing to a file
  • ObjectInputStream – for writing objects to a stream
  • ByteArrayOutputStream – It is used to write the array of bytes
  • PipeOutputStream – It is used for writing to a piped stream
  • FilterOutputStream – it is used for filtering the output from an end stream

The Standard Streams

Your operating system will typically define three standard streams that are accessible through members of the system class in java:

  • A Standard input stream that corresponds to the particular keyboard will be the default. This is encapsulated by the in a member of the system class and is of the type input stream.
  • A Standard output stream will always correspond to the command line of the output. This is encapsulated by the out member of the system class and is of type print stream.
  • A Standard error output stream for error messages that usually maps to the command-line output by default. It is also encapsulated by err members of a class system and print stream.

Reading and Writing Files

Reading files

The process we use for reading a file is quite similar to writing a file. First, you will obtain a file channel of an object from a file stream and also use the same channel to read the data for one or more buffers. Initially, you will be using a channel object that you obtain from a FileInputStream object to read a file. Later you will be using a FileChannel object obtained from a RandomAccessFile object to read and write the same file.

A FileInputStream object encapsulates a file that is essentially intended to be read, so the file must already exist and contain some data.


FileInputStream inputFile = null;  
          // place to store the input stream reference
Try {
     inputFile = new FileInputStream(*C:/Beg Java Stuff/myFile.txt*);
Catch(FileNotFoundException e) {

Creating File Input Streams

A FileInputStream object encapsulates a file that it wants to read but it should already exist in the file and should also contain some data to read. It says that the constructor of a class in an object will be created in file only if it already exists.

There is a possibility even to use a file object that you have obtained by calling the getFD() method for an existing FileInputStream object, or possibly a random access file object. 

File aFile = new File(* C:/Beg Java Stuff/myFile.text*);
FileInputStream inputFile1=null;
FileDescriptor fd=null;

Try {
   // create the stream opened to write
   inputFile1=new FileInputStream(aFile);
} catch (IOException e)   {

// you can now create another input stream for the file from the file descriptor…
    FileInputStream inputFile2=new FileInputStream(fd); 

Once you have created the ObjectInputStream object, you call its readObject() method to read an object from the file.

Object myObject = null;
Try {
    myObject = objectIn.readObject();

}  catch(ClassNotFoundException e) {

} catch(IOException e) {

Writing Files

The process for writing a file is basically quite simple. For writing a file, you will load a file that you have created as one or more buffers and call a method for that particular object to write data to that file which is encapsulated by the file stream. 

To start with, you will be using the simplest write() method for a file channel that writes the data contained in a single ByteBuffer object to a file. The number of bytes written to the file is determined by the buffers position and limit when the write() method executes.

To create a file in a specific directory, specify the path of the file and use double black slashes to escape the “\” character.



File theFile = new File(“ MyFile”);
   //Check out the file…

   //Create the object output stream for the file
   ObjectOutPutStream objectOut = null;
   Try {
       Objectout = new ObjectOutputStream(new FileOutputStream(theFile))

The five different exceptions that a channel write() operation will throw:



canread() – It is a Boolean type and it says whether the file which we want is readable or not.

canwrite() – It is a Boolean type and it says whether the file which we want is writable or not.

createnewfile() – It is a Boolean type that says that the method creates an empty file.

delete() – It is a Boolean type which deletes a file which we want.

exist() – It is a Boolean type and says whether the file exists or not.

getname() – It is a string type which returns the file name or name of the file.

getabsolutepath() –  It is a string type which returns the correct path of name of the file.

length() – It is a long type which returns the wanted size of the file in bytes.

list() – It is a string type which returns the array of the file in the directory.

mkdir() – It is a Boolean type which creates a directory.

File navigation and I/O

This concept comes as an input and output of a file where the flow of data that either you can read or you can write or you can perform read and write operations in a file permanently. Java uses these input and output streams to perform these tasks.


  • InputStream
    • FileInputStream
    • ByteArrayInputStream
    • FileInputStream  
    • ObjectInputStream
    • OutPutStream
  • FileOutputStream
    • ByteArrayOutputStream
    • FileOutputStream
    • ObjectOutputStream

An overview of file navigation and I/O is above diagram

Image result for java file navigation and io in java

Java Directories

Creating and Modifying Files and Directories directory 

renameTo(File path)The file represented by the current object will be renamed to the path represented by the File object passed as an argument to the method. This does not change the current file object in your program and it alters the physical file.
setreadonly()Sets the file represented by the current object as read-only and returns true if the operation is successfully.
mkdir()Creates a directory with the path specified by the current file object.
mkdirs()Creates the directory represented by the current file object, including parent directories that are required.
createnewfile()Create a new empty file with the pathname defined by the current file object as long as the file does exist.
delete()This will delete the file and directory represented by the current file object and return true if the delete is successful.

Querying Files and Directories

exists()Returns true if the file or directory referred to by the file object exists and false otherwise.
isfile()Returns true if the file object refers to an existing file and false otherwise.
canread()Returns true if you are permitted to read the file referred by the file object.
canwrite()Returns true if you are permitted to write the file referred by the file object.

This brings us to the end of the blog on File Handling in Java. If you found this helpful and wish to learn more such concepts, you can check out our various free online courses available on Great Learning Academy.



Please enter your comment!
Please enter your name here

6 − 3 =