Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

 Core Java - File Handling and I/O

14. File Handling and I/O

File handling and I/O operations are essential for reading from and writing to files in Java. These operations allow you to interact with files, perform data input and output, and manipulate file content. In this Core Java tutorial, we'll explore file handling and I/O in detail, providing explanations and examples.

Reading from a File:

To read data from a file in Java, you typically use the 'FileInputStream', 'FileReader', or 'BufferedReader' classes.

  • Using 'FileInputStream' (Byte Streams):

'FileInputStream' is used to read binary data from a file. You can wrap it in a 'BufferInputStream' for improved performance.

import java.io.FileInputStream;
import java.io.IOException;

public class ReadFileExample {
    public static void main(String[] args) {
        try (FileInputStream fileInputStream = new FileInputStream("myfile.txt")) {
            int data;
            while ((data = fileInputStream.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 

In this example, 'FileInputStream' is used to read bytes from the file '"myfile.txt"', and we convert the bytes to characters for display.

  • Using 'FileReader' (Character Streams):

'FileReader' is used to read character data from a file. Wrapping it in a 'BufferedReader' can improve performance and provide line-by-line reading.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileExample {
    public static void main(String[] args) {
        try (BufferedReader reader = new BufferedReader(new FileReader("myfile.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 

In this example, we use 'FileReader' to read character data from the file '"myfile.txt"' line by line.

Writing to a File:

To write data to a file in Java, you can use 'FileOutputStream', 'FileWriter', or 'BufferedWriter' classes.

  • Using 'FileOutputStream' (Byte Streams):

'FileOutputStream' is used to write binary data to a file. Wrapping it in a 'BufferedOutputStream' can improve performance.

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

public class WriteFileExample {
    public static void main(String[] args) {
        try (FileOutputStream fileOutputStream = new FileOutputStream("output.txt")) {
            String data = "Hello, World!";
            byte[] bytes = data.getBytes();
            fileOutputStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 

In this example, we use 'FileOutputStream' to write the string  '"Hello, World!"' to the file '"output.txt"' .

  • Using 'FileWriter' (Character Streams):

'FileWriter' is used to write character data to a file. Wrapping it in a 'BufferedWriter' can improve performance and provide line-by-line writing.

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFileExample {
    public static void main(String[] args) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
            String data = "Hello, World!";
            writer.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 

In this example, we use 'FileWriter' to write the string '"Hello, World!"' to the file '"output.txt"'.

Closing Resources with 'try-with-resources'

In the examples above, we use the 'try-with-resources' statement to automatically close resources like file streams and readers/writers. This ensures that resources are properly closed even if an exception occurs.

File and Directory Manipulation

Java provides classes like 'File' and 'Path' to perform file and directory manipulation tasks, such as checking file existence, creating directories, and listing directory contents.

Example:
import java.io.File;

public class FileManipulationExample {
    public static void main(String[] args) {
        // Check if a file exists
        File file = new File("myfile.txt");
        if (file.exists()) {
            System.out.println("File exists.");
        }

        // Create a directory
        File directory = new File("mydir");
        if (!directory.exists()) {
            if (directory.mkdir()) {
                System.out.println("Directory created.");
            } else {
                System.out.println("Failed to create directory.");
            }
        }

        // List files in a directory
        File[] files = directory.listFiles();
        if (files != null) {
            for (File f : files) {
                System.out.println("File: " + f.getName());
            }
        }
    }
}
 

In this example, we check if a file exists, create a directory, and list files in a directory.

Conclusion:

File handling and I/O operations are essential for many Java applications, especially those that deal with data storage and retrieval. Understanding how to read from and write to files, manipulate directories, and manage resources properly is crucial for building robust and reliable Java programs.