bscodinglab

File Handling

File handling in Java allows you to read from and write to files, which is a fundamental part of working with data. Java provides various classes and methods in the java.io and java.nio packages to work with files. Here’s an overview of file handling in Java.

Why File Handling is Required :-

  • File Handling is an integral part of any programming language as file handling enables us to store the output of any particular program in a file and allows us to perform certain operations on it.
  • In simple words, file handling means reading and writing data to a file.
  • Configuration: Configuration files, like properties files or JSON files, are commonly used to store application settings, preferences, or parameters. File handling allows you to read and modify these settings easily.
  • Logging: Logging is essential for debugging and monitoring the behavior of Java applications. You can use file handling to write log entries to files for later analysis.
  • Data Import/Export: File handling is useful for importing data from external sources, such as CSV files or databases. Similarly, you can export data from your Java applications to files in various formats for sharing or backup purposes.
  • Database Backup: Many applications require periodic backups of their database contents. File handling allows you to save these backups as files.
  • Report Generation: If your application generates reports or documents, file handling is necessary to save these reports as files on the file system.
  • Resource Management: Java applications often need to manage external resources like images, audio files, or other binary data. File handling helps you load and save these resources.
  • Data Analysis: For data analysis or scientific computing, reading data from files is a common way to work with datasets that are too large to fit in memory.
  • Interacting with External Systems: In enterprise applications, Java often interacts with external systems by reading and writing files. For example, you might need to process incoming files from clients or generate files to send to other organizations.
  • Handling User Input/Output: When your Java application needs to take user input or present output, file handling can be used to read input from text files and display output in files.

Streams in Java :-

  • In Java, a sequence of data is known as a stream.
  • This concept is used to perform I/O operations on a file.
  • There are two types of streams :

Input Stream:-

In Java, an input stream is a fundamental concept for reading data from various input sources, such as files, network connections, or other input streams. Input streams are part of the Java I/O (Input/Output) library, and they provide a way to read data sequentially from the source. The java.io package, which has been around since the early days of Java, offers several classes for working with input streams.

There are several subclasses of the InputStream class, which are as follows:

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

Creating an InputStream

// Creating an InputStream

InputStream obj = new FileInputStream();

Here, an input stream is created using FileInputStream.

Methods of InputStream :-

S/No.MethodDescription
1read()Reads one byte of data from the input stream.
2read(byte[] array)()Reads byte from the stream and stores that byte in the specified array.
3mark()It marks the position in the input stream until the data has been read.
4available()Returns the number of bytes available in the input stream.
5markSupported()It checks if the mark() method and the reset() method is supported in the stream.
6reset()Returns the control to the point where the mark was set inside the stream.
7skips()Skips and removes a particular number of bytes from the input stream.
8close()Closes the input stream.

Output Stream:

In Java, an output stream is a fundamental concept for writing data to various output destinations, such as files, network connections, or other output streams. Output streams are part of the Java I/O (Input/Output) library and provide a way to write data sequentially to the target destination. The java.io package offers several classes for working with output streams.

The OutputStream class is an abstract superclass for all output streams in Java. It defines the basic methods for writing data. Here are some of the key methods available in the OutputStream class:

There are several subclasses of the OutputStream class which are as follows:

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

Creating an OutputStream

// Creating an OutputStream

OutputStream obj = new FileOutputStream();

Here, an output stream is created using FileOutputStream.

Methods of OutputStream

S/No.MethodDescription
1write()Writes the specified byte to the output stream.
2write(byte[] array)Writes the bytes which are inside a specific array to the output stream.
3close()Closes the output stream.
4flush()Forces to write all the data present in an output stream to the destination.

File Class Methods :-

The java.io.File class provides methods for working with files and directories in Java. This class allows you to create, manipulate, and obtain information about files and directories. Here are some commonly used methods of the File class:

 

  1. Creating a File/Directory:
    • boolean createNewFile(): Creates a new, empty file if it doesn’t already exist. Returns true if the file was created successfully.
    • boolean mkdir(): Creates the directory specified by this File Returns true if the directory was created successfully.
    • boolean mkdirs(): Creates the directory specified by this File object, including any necessary but nonexistent parent directories.
  2. File Information:
    • String getName(): Returns the name of the file or directory.
    • String getPath(): Returns the path of the file or directory as a string.
    • String getAbsolutePath(): Returns the absolute path of the file or directory.
    • boolean isFile(): Checks if the File object represents a file.
    • boolean isDirectory(): Checks if the File object represents a directory.
    • boolean exists(): Checks if the file or directory exists.
    • long length(): Returns the size of the file in bytes.
    • long lastModified(): Returns the time the file was last modified as a long
  3. File Operations:
    • boolean delete(): Deletes the file or directory. Returns true if the deletion was successful.
    • boolean renameTo(File dest): Renames the file or moves it to a new location specified by the dest
  4. Listing Files in a Directory:
    • String[] list(): Returns an array of strings containing the names of files and directories in the current directory.
    • File[] listFiles(): Returns an array of File objects representing files and directories in the current directory.
  5. Checking Permissions:
    • boolean canRead(): Checks if the file or directory can be read.
    • boolean canWrite(): Checks if the file or directory can be written to.
    • boolean canExecute(): Checks if the file or directory can be executed.
  6. Other Methods:
    • boolean isHidden(): Checks if the file is hidden.
    • boolean setReadOnly(): Sets the file or directory to be read-only.
    • boolean setExecutable(boolean executable): Sets the execute permission for the file or directory.
    • File getParentFile(): Returns the parent directory as a File
  7. File Paths:
    • static File[] listRoots(): Returns an array of File objects representing the available file system roots.

 

S/No.MethodDescriptionReturn Type
1canRead()It tests whether the file is readable or not. Boolean
2canWrite()It tests whether the file is writable or not.Boolean
3createNewFile()It creates an empty file.Boolean
4delete()It deletes a file.Boolean
5exists()It tests whether the file exists or not.Boolean
6length()Returns the size of the file in bytes.Long
7getName()Returns the name of the file.String
8list()Returns an array of the files in the directory.String
9mkdir() Creates a new directory.Boolean
10getAbsolutePath()Returns the absolute pathname of the file.String

Let us now get acquainted with the various file operations in Java. 
File operations in Java :-

  1. Create a File
  2. Reading from a File:
  3. Writing to a File:
  4. Delete a File
  5. Using Java NIO (New I/O):
  1. Create a File :- To create a new file in Java, you can use the File class from the java.io package. Here’s how you can create a file:

Example :-

     public void CreateFile()

             {

        // Specify a file name and path

        String fileName = “example.txt”;

        // Create a new file

        try {

            File file = new File(fileName);

            if (file.createNewFile())

             {

                        System.out.println(“File created: ” + file.getName());

               }

                     else {

                          System.out.println(“File already exists.”);

                             }

        }

         catch (IOException e)

                  {

                 System.err.println(“An error occurred while creating the file.”);

        e.printStackTrace();

                }

}

In this example :-

  • We specify the name of the file we want to create, in this case, “example.txt.”
  • We create a File object with the specified file name.
  • We use the createNewFile() method to attempt to create the file. If the file doesn’t exist, it will be created, and the method will return true. If the file already exists, it returns false.
  • We handle any potential exceptions that may occur during file creation.

 Note :- Make sure you specify the correct file name and path based on your requirements. 

  1. Reading from a File :- Reading from a file in Java is a common operation that allows you to access and process data stored in files. To perform file reading operations, you can use the java.io or java.nio packages.

Here are the basic steps to read from a file in Java:

  • Open the File: You need to open the file that you want to read. You can use the FileInputStream, FileReader, or other classes to achieve this.
  • Read Data: Use appropriate methods to read data from the file. The choice of class and method depends on whether you are reading text or binary data.
  • Close the File: After you’re done reading, it’s essential to close the file to release system resources.

Example :-

public void ReadFile()

 {

        // Read data from the file

        try {

            FileReader reader = new FileReader(fileName);

            BufferedReader bufferedReader = new BufferedReader(reader);

            String line;

            System.out.println(“Reading data from the file:”);

            while ((line = bufferedReader.readLine()) != null)

                {

                        System.out.println(line);

                  }

               reader.close();

               }

catch (IOException e)

                {

            System.err.println(“An error occurred while reading from the file.”);

            e.printStackTrace();

                  }

}

In this example :-

In this example, we open a file called “FileName.txt,” read its contents line by line, and print them to the console. The try-with-resources block is used to ensure that the file is properly closed after reading, even if an exception occurs.

For binary data or more advanced file manipulation, consider using classes like FileInputStream, BufferedInputStream, or java.nio.file utilities.

  1. Writing to a File :- In Java, you can perform various file operations, including writing to a file, using classes from the java.io package or the java.nio package.

Using io package (Stream-based approach) :- In this approach, you typically use FileOutputStream or FileWriter to write data to a file.

Example :

  import java.io.FileWriter;

            import java.io.IOException;

            public class WriteToFileExample

             {

            public static void main(String[] args)

                    {

                        String content = “Hello, world!”;

                        String fileName = “example.txt”;

                                try {

                                                      FileWriter writer = new FileWriter(fileName);

     writer.write(content);

      writer.close();

       System.out.println(“Data written to ” + fileName);

                                }

               catch (IOException e)

                                           {

                                           e.printStackTrace();

                                    }

                 }

                       }

  1. Delete a File :- In Java, you can delete a file using the java.io.File class. Here are three common methods to delete a file:

Using the delete() method :-  You can use the delete() method of the File class to delete a file. This method returns true if the file was successfully deleted and false if the file could not be deleted for some reason (e.g., the file does not exist).

Example :

import java.io.File;

public class FileDeletionExample

{

public static void main(String[] args)

  {

      String filePath = “path/to/your/file.txt”; // Replace with the path to the file you want to delete

       File file = new File(filePath);

       if (file.delete())

             {

                                    System.out.println(“File deleted successfully.”);

            }

        else

             {

                          System.out.println(“Failed to delete the file.”);

             }

         }

        }

  1. Using Java NIO (New I/O)

1. WriteToFile :-

Using java.nio package (Channel-based approach) :- In this approach, you use the FileChannel and ByteBuffer to write data to a file.

Example :

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class WriteToFileNIOExample
{
public static void main(String[] args)
  {
     String content = "Hello, world!";
     Path filePath = Path.of("example.txt");
     
try (FileChannel channel = FileChannel.open(filePath,StandardOpenOption.WRITE,
StandardOpenOption.CREATE))   {      ByteBuffer buffer = ByteBuffer.wrap(content.getBytes());         int bytesWritten = channel.write(buffer);         System.out.println("Wrote " + bytesWritten + " bytes to " + filePath);        } catch (IOException e)        {           e.printStackTrace();        }   } }

In examples:

  • You specify the name of the file you want to write to (e.g., “example.txt”).
  • You open the file for writing using the appropriate classes (FileWriter and BufferedWriter in the java.io approach, or Files and StandardOpenOption in the java.nio approach).
  • You write content to the file, and you can use newLine() to add new lines.
  • After writing the content, you should close the file to ensure that all changes are saved and resources are released.

2. Delete To File :-

Using the Files class from Java NIO (Java 7 and later) :- You can also use the Files.delete(Path path) method from the java.nio.file package to delete a file.

Example :-

import java.io.IOException;

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

public class FileDeletionExample

{

public static void main(String[] args)

{

String filePath = “path/to/your/file.txt”; // Replace with the path to the file you want to delete Path path = Paths.get(filePath);

try {

Files.delete(path);

System.out.println(“File deleted successfully.”);

}

catch (IOException e)

{

System.err.println(“Failed to delete the file: ” + e.getMessage());

}

}

}

Complete Example of file Handling :-

import java.io.File;

import java.io.IOException;

import java.io.FileWriter;

import java.io.FileReader;

import java.io.BufferedReader;

public class FileHandlingExample

    {

public static void main(String[] args)

    {

// Specify a file name and path

String fileName = “example.txt”;

// Create a new file

try {

File file = new File(fileName);

if (file.createNewFile())

{

System.out.println(“File created: ” + file.getName());

  }

         else {

   System.out.println(“File already exists.”);

      }

}

catch (IOException e)

{

System.err.println(“An error occurred while creating the file.”);

e.printStackTrace();

  }

// Write data to the file

try {

FileWriter writer = new FileWriter(fileName);

writer.write(“Hello, this is an example of file handling in Java.”);

writer.close();

System.out.println(“Data written to the file.”);

    }

catch (IOException e)

       {

  System.err.println(“An error occurred while writing to the file.”);

   e.printStackTrace();

}

// Read data from the file

try {

FileReader reader = new FileReader(fileName);

BufferedReader bufferedReader = new BufferedReader(reader);

String line;

System.out.println(“Reading data from the file:”);

while ((line = bufferedReader.readLine()) != null)

    {

System.out.println(line);

     }

     reader.close();

          }

     catch (IOException e)

           {

System.err.println(“An error occurred while reading from the file.”);

e.printStackTrace();

   }

// Check if the file exists

File checkFile = new File(fileName);

if (checkFile.exists())

{

System.out.println(“The file exists.”);

}

      else {

 System.out.println(“The file does not exist.”);

     }

// Delete the file

if (checkFile.delete())

{

System.out.println(“File deleted: ” + fileName);

}

     else {

System.out.println(“Failed to delete the file.”);

}

}

}

Output :-