T E C h O C E A N H U B

File input/output operations

File input/output operations in Java involve reading from and writing to files on the system. The java.io package provides classes and methods to perform file operations. Here’s an overview of the basic file input/output operations in Java:

  1. Reading from a File:
    • Create a File object, specifying the path to the file.
    • Create a FileReader or BufferedReader object, passing the File object as a parameter.
    • Use the read() or readLine() method to read data from the file.
    • Close the file using the close() method when finished.

Example:

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

public class FileReadExample {
    public static void main(String[] args) {
        try {
            File file = new File("path/to/file.txt");
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }

            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}





  1. Writing to a File:
    • Create a File object, specifying the path to the file.
    • Create a FileWriter or BufferedWriter object, passing the File object as a parameter.
    • Use the write() method to write data to the file.
    • Close the file using the close() method when finished.

Example:

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

public class FileWriteExample {
    public static void main(String[] args) {
        try {
            File file = new File("path/to/file.txt");
            FileWriter fileWriter = new FileWriter(file);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

            bufferedWriter.write("Hello, World!");
            bufferedWriter.newLine(); // Write a new line

            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}




Remember to handle exceptions appropriately when working with file input/output operations in Java, as they can occur if the file is not found, permissions are insufficient, or other issues arise.

Copyright ©TechOceanhub All Rights Reserved.