File Handling in Java

Hi guys, welcome back. In this module, I will be discussing file handling in Java. After reading this module, you will get to know file handling operations in Java. Let’s know about Java file handling without any further delay.

File Handling in Java

File Handling in Java

File handling is an essential part of any programming language. Using files, a program can store data on a storage device. To perform various actions on a file, such as read, write, and so on, file handling is required.

File handling is defined as reading from a file and writing to a file. We can use the File class in Java to create a file object. The package java.io contains a File class to work and handle different formats of files. If you want to use the File class, you need to create an object of the File class and provide the name of the file or pathname. Using file class we can access metadata of files such as file name, file size, permissions, type of file, etc.

// importing all the classes of java.io
import java.io.*;
class FileHandle {
    public static void main(String[] arr) {
       // an object of File class is created.
       File f=new File("demo.txt");
}
}

Note: You can give an absolute pathname if you are not in the current working directory.

You can also use import java.io.File instead of using import java.io.* to import File class in Java. Now, let’s know about streams because Java uses Streams to perform input-output (I/O) operations on a file.

What is a Stream in Java?

A stream is a sequence of data. It is also defined as a sequence of bytes. It can be used to represent either an input source or a destination. The source and destination can be disk files, arrays, text files, etc. The input stream reads or retrieves data from a source, whereas the output stream writes data to a destination. There are two types of streams:

Byte stream

Byte Stream is used to performing read and write operations with byte data. A byte stream file handling process is defined as when the given input is executed using byte data. There are many classes provided related to byte streams but the most often used classes are FileInputStream and FileOutputStream.

import java.io.*;
public class FileHandle{
   public static void main(String []arr) throws IOException{
   FileInputStream fin=new FileInputStream("source_file.txt");
   FileOutputStream fout=new FileOutputStream("destination_file.txt");
   int character;
   while((character=fin.read())!=-1)
   {
      System.out.print((char)character);
      // writing to destination file
      fout.write((char)character);
   }
   // closing source_file.txt
   fin.close();
   // closing destination_file.txt
   fout.close();
 }
}

In the above example, we are reading data from the source file and writing data to a destination. -1 indicates the end of the file. So, reading from the source file will be stopped when -1 is encountered.

Character stream

Character Stream is used to performing read and write operations with character data. The file handling process with a character stream is the process of executing input data with characters. There are many character stream classes available, but the most commonly used classes include FileWriter and FileReader.

Now, let’s discuss some of the File class methods in Java.

What are the File class methods in Java?

  • canRead()

    This file class method checks whether the file is readable or not and returns a Boolean value i.e., true or false.

  • canWrite()

    This is a file class method that checks whether the file is writable or not and returns a Boolean value i.e., true or false.

  • exists()

    It is a file class method used to check whether the given file is present or not and returns a boolean value.

  • createNewFile()

    When we want to create a new empty file, use this file class method. It returns a Boolean value.

  • delete()

    It is a file class method used for deleting a file and returns a Boolean value.
    getAbsolutePath()
    This method is used to return the absolute pathname of the file.

  • getName()

    It is a method used to return a string value which is the name of the file.

  • list()

    It returns an array of strings representing all the files in the directory.

  • length()

    This method of the file class returns the file’s size in bytes.

  • mkdir()

    It is a method of file class that is used to create a new directory.

Let’s look at the various file operations available in Java and how to use them.

What are the file operations in Java?

In Java file handling, we can do the following operations on a file:

  1. Creating a file
  2. Writing data to a file
  3. Reading data from a file
  4. Deleting a file
  5. Getting information of a file

Creating a file

In Java, we can create a file using the createNewFile() method of the File class. This method returns true if the file is created, otherwise, false is returned if the file already exists.

import java.io.*;
public class FileHandle{
   public static void main(String []arr) throws IOException{
   // an object of file class
   File f=new File("demo.txt");
   // creating a new file
   Boolean result=f.createNewFile();
   if(result)
      System.out.print(f+" created successfully.");
   else
      System.out.format("%s","File cannot be created due to some error.");
 }
}

Writing data to a file

The write operation on a file means storing the data in a file. To perform write operations on a file, we will use the write() method along with the FileWriter class. We should use the close() method to close the stream to retrieve the allocated resources.

import java.io.*;
public class FileHandle{
   public static void main(String []arr) throws IOException{
     // creating a new file and writing data to a file
     FileWriter fw=new FileWriter("demo.txt");
     String s="Welcome, this is tutorial of Java File Handling.";
     fw.write(s);
     // closing a file
     fw.close();
   }
}

Reading from a file

The read operation means to access or retrieve the data stored from a file. To perform write operation on a file, we will use Scanner class along with hasNextLine() and nextLine() methods to retrieve data from a file. We should use the close() method to close the stream.

import java.io.*;
import java.util.Scanner;
public class FileHandle{
   public static void main(String []arr) throws IOException{
     File f=new File("demo.txt");
     Scanner sc=new Scanner(f);
     while(sc.hasNextLine())
     {
       String str=sc.nextLine();
       System.out.println(str);
     }
     // closing a file
     sc.close();
   }
}

Deleting a file

In Java file handling, we can delete a file using the delete() method of the File class.
There is no need to close the file using close() because neither the FileWriter nor the Scanner classes are used to delete a file.

import java.io.*;
public class FileHandle{
   public static void main(String []arr) throws IOException{
      File f=new File("demo.txt");
      Boolean result=f.delete();
      if(result)
         System.out.print(f+" deleted successfully.");
      else
         System.out.format("%s","File cannot be deleted due to some error.");
   }
}

Getting file information

There are few methods in Java that I have discussed earlier at methods of file class to get the information of the file.

import java.io.*;
public class FileHandle{
   public static void main(String []arr) throws IOException{
     File file=new File("demo.txt");
     file.createNewFile();
     String filename=file.getName();
     System.out.println("File Name is "+filename);
     System.out.println("Absolute path of "+filename+" : "+file.getAbsolutePath());
     System.out.print("length of "+filename+" : "+file.length());
     System.out.println("Is "+filename+" readable? "+file.canRead());
     System.out.println("Is "+filename+" writable? "+file.canWrite());
     System.out.println("Is "+filename+" exists? "+file.exists());
  }
}

Now, let’s see one Java program to find whether a number is even or odd using a byte array stream in Java file handling.

How to write a Java program to find odd or even numbers using a byte array stream in file handling?

We will be using ByteArrayInputStream class to write the given program. In Java, a ByteArrayInputStream contains a buffer that is used to read a byte array as an input stream. The package java.io provides the ByteArrayInputStream class. Given below is the code to check for even or odd numbers.

import java.io.*;
public class FileHandle{
   public static void main(String []arr) throws IOException{
     byte []buffer={10,40,81,23,32,100,57};
     ByteArrayInputStream by=new ByteArrayInputStream(buffer);

     int character=0;
     while((character=by.read())!=-1)
     {
        int number=character;
        if(number%2==0)
          System.out.println(number+" is an even number.");
        else
          System.out.println(number+" is an odd number.");
     }
   }
}

I hope this module might be useful for you to understand file handling in Java. You should try to implement all the methods of file and operations by yourself to gain a better understanding. Keep in touch with us for more informative modules like this. Keep practicing!