Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

File Handling in Java

Java is one of the world’s most widely used programming languages and is known for its ability to handle a wide range of tasks and problems. One of these tasks is reading and writing data from and to a file, commonly referred to as file handling. File handling in java is a critical aspect of programming. Java provides several classes and methods that help developers perform various operations on files and directories. This article will take a comprehensive look at file handling in Java and how it can be implemented in your programs.

What is File Handling in Java?

File handling in Java refers to the process of reading and writing data from and to a file in a Java program. The file can be a text file, an image file, or any other type of data that can be stored in a file. The goal of file handling is to allow a program to access data stored in a file, manipulate it, and write it back to the file.

We can work with files in Java thanks to the File Class. This File Class is part of the java.io package. Create an object of the File class and then specify the name of the file to use it.

Example of File Handling

// Importing File Class
import java.io.File;

class Main {
    public static void main(String[] args)
    {

        // File name specified
        File obj = new File("myPrepBytesfile.txt");
        System.out.println("File Created!");
    }
}

To conduct I/O operations on a file in Java, the concept Stream is used. So, first and foremost, let us become familiar with the concept of Stream in Java.

What is a Stream in Java?

Stream is a concept of Java that pipelines a series of objects to achieve the desired output. A stream is not a data structure; it just accepts input from a collection of I/O.

A stream can be divided into two types: input streams and output streams.

Input Stream

The superclass of all input streams is Java InputStream. The input stream is used to read data from various input devices such as the keyboard, network, and so on. Because InputStream is an abstract class, it is useless by itself. However, subclasses InputStream are used to read data.

The Input Stream class has the following subclasses:

  • ByteArrayInputStream
  • FileInputStream
  • AudioInputStream
  • StringBufferInputStream
  • FilterInputStream
  • ObjectInputStream

Let’s create an InputStream

// Creating an InputStream
InputStream Buddy = new FileInputStream();

Here, FileInputStream is used to create an InputStream.

Methods of Input Stream

The InputStream class in Java provides several methods for reading data, including the following:

  • int read(): This method reads the next byte of data from the input stream and returns it as an int in the range 0 to 255.If the stream has reached the end, it returns -1.
  • int read(byte[] b): This method reads up to b.length bytes of data from the input stream into an array of bytes. It returns the total number of bytes read into the buffer, or -1 if no more data can be read since the stream has reached its end.
  • int read(byte[] b, int off, int len): This method reads up to len bytes of data from the input stream into an array of bytes starting at an offset of off within the buffer. It returns the total amount of bytes read into the buffer, or -1 if there is no further data since the stream has reached its end.
  • long skip(long n): This method skips over and discards n bytes of data from the input stream. It returns the number of bytes that were actually skipped.
  • int available(): This method returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
  • void close(): This method closes the input stream and releases any system resources associated with the stream.

Note: It is a good practice to always close the input stream after you are done with it to release the resources it is holding.

Output Stream

The output stream is used to write data to a variety of output devices such as the display, file, and so on. OutputStream is an abstract superclass that represents an output stream. Because OutputStream is an abstract class, it is useless on its own. Its subclasses, on the other hand, are used to write data.

The Output Stream class has the following subclasses:

  • FileOutputStream
  • StringBufferOutputStream
  • ByteArrayOutputStream
  • PrintStream
  • ObjectOutputStream
  • DataOutputStream

Let’s create an OutputStream

// Creating an OutputStream
OutputStream Buddy = new FileOutputStream();

Here, FileOutputStream is used to create an OutputStream.

Methods of Output Stream

The OutputStream class in Java provides several methods for writing data, including the following:

  • void write(int b): This method writes the specified byte to the output stream.
  • void write(byte[] b): This method writes b.length bytes from the specified byte array to the output stream.
  • void write(byte[] b, int off, int len): This method writes len bytes from the specified byte array starting at an offset of off within the buffer to the output stream.
  • void flush(): This method flushes any buffered output bytes to the underlying output device.
  • void close(): This method closes the output stream and releases any system resources associated with the stream.

Note: It is a good practice to always close the output stream after you are done with it to release the resources it is holding.

Java File Class Methods

The java.io.File class in Java provides several methods for working with files and directories, including the following:

  • boolean exists(): This method returns true if the file or directory specified by the File object exists, and false otherwise.
  • boolean isDirectory(): This method returns true if the File object represents a directory, and false otherwise.
  • boolean isFile(): This method returns true if the File object represents a regular file, and false otherwise.
  • String getName(): This method returns the name of the file or directory specified by the File object.
  • String getAbsolutePath(): This method returns the absolute pathname of the file or directory specified by the File object.
  • long length(): This method returns the size, in bytes, of the file specified by the File object.
  • String[] list(): This method returns an array of strings naming the files and directories in the directory specified by the File object.
  • File[] listFiles(): This method returns an array of File objects for the files and directories in the directory specified by the File object.
  • boolean createNewFile(): This method creates a new, empty file with the name specified by the File object and returns true if the file was created successfully, and false otherwise.
  • boolean delete(): This method deletes the file or directory specified by the File object and returns true if the file or directory was deleted successfully, and false otherwise.
  • boolean mkdir(): This method creates a new directory with the name specified by the File object and returns true if the directory was created successfully, and false otherwise.
  • boolean mkdirs(): This method creates a new directory with the name specified by the File object, including any necessary but nonexistent parent directories, and returns true if the directory was created successfully, and false otherwise.
  • boolean renameTo(File dest): This method renames the file or directory specified by the File object to the file or directory specified by the dest File object and returns true if the file or directory was renamed successfully, and false otherwise.

Let us now become acquainted with the various file operations available in Java.

File Operations in Java

Here are some common file operations in Java:

Create

In Java, the createNewFile() method can be used to create a file. If the file is successfully created, it will return the Boolean value true, else it will return false. The following is an example of how to create a file in Java:

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

public class Main {
    public static void main(String[] args)
    {

        try {
            File prepObj = new File("myfile.txt");
            if (prepObj.createNewFile()) {
                System.out.println("File created: "
                                + prepObj.getName());
            }
            else {
                System.out.println("File already exists.");
            }
        }
        catch (IOException e) {
            System.out.println("An error has occurred.");
            e.printStackTrace();
        }
    }
}

Output:

An error has occurred.

Read

To read the contents of a file, we’ll use the Scanner class. Here’s an example of how to read the contents of a file in Java:

import java.io.File;
import java.io.FileNotFoundException;
// Import the Scanner class to read content from text files
import java.util.Scanner;

public class Main {
    public static void main(String[] args)
    {
        try {
            File Obj = new File("myfile.txt");
            Scanner Reader = new Scanner(Obj);
            while (Reader.hasNextLine()) {
                String data = Reader.nextLine();
                System.out.println(data);
            }
            Reader.close();
        }
        catch (FileNotFoundException e) {
            System.out.println("An error has occurred.");
            e.printStackTrace();
        }
    }
}

Output:

An error has occurred.

Write

In order to write text to a file, we use the FileOutputStream class and its write() method. The following is an example of how to write text to a file in Java:

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

public class Main {
  public static void main(String[] args) {
    File obj = new File("example.txt");
    String content = "This is a sample file content.";
    try {
      FileOutputStream fos = new FileOutputStream(obj);
      fos.write(content.getBytes());
      System.out.println("Successfully written");
      fos.close();
    } catch (IOException e) {
      System.out.println("Error Encounter");
      e.printStackTrace();
    }
  }
}

Output:

Error Encounter

Delete

We use the delete() method in order to delete a file. Following is an example of how to delete a file in Java:

import java.io.File;

public class Main {
  public static void main(String[] args) {
    File obj = new File("example.txt");
    if (obj.delete()) {
      System.out.println("File deleted successfully.");
    } 
    else {
      System.out.println("File delete failed.");
    }
  }
}

Output:

File delete failed.

Conclusion
So, in this article, we looked at file handling in Java. This is an important concept since it allows us to automate the content of a file using code, which can save us a lot of time. We learned how to create, read, write, and delete files from our system.

FAQs on File Handling in Java

Below are some frequently asked questions (FAQs) on file handling in Java:

Question 1- What is the File class in Java?
Answer– The File class in Java is a class that represents a file or directory in the file system. It provides methods for creating, deleting, and manipulating files and directories, as well as for accessing information about files and directories.

Question 2 – What is the difference between File and FileInputStream in Java?
Answer– The File class in Java is used for manipulating files and directories, whereas the FileInputStream class is used for reading binary data from a file. The FileInputStream class extends the InputStream class, which is a superclass of all input stream classes in Java.

Question 3 – What is the difference between File and FileOutputStream in Java?
Answer– The File class in Java is used for manipulating files and directories, whereas the FileOutputStream class is used for writing binary data to a file. The FileOutputStream class extends the OutputStream class, which is a superclass of all output stream classes in Java.

Question 4 – What is the difference between reading a text file and a binary file in Java?
Answer– Reading a text file in Java involves reading characters from the file, whereas reading a binary file involves reading bytes from the file. Text files are human-readable, whereas binary files are not. The difference between reading a text file and a binary file in Java is primarily a matter of the type of input stream used to read the data.

Question 5 – How can I read a text file in Java?
Answer– To read a text file in Java, you can use the FileReader class, which is a subclass of the Reader class. You can create a FileReader object from a File object, and then use the read method to read characters from the file.

Question 6 – How can I read and write binary data in Java?
Answer– To read binary data in Java, you can use the FileInputStream class, which extends the InputStream class. To write binary data in Java, you can use the FileOutputStream class, which extends the OutputStream class.

Leave a Reply

Your email address will not be published. Required fields are marked *