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

Reading from and writing to files in java

In Java, you can read from and write to files using various classes from the java.io package. Here’s an example of how you can perform file reading and writing operations:

  • Reading from a File:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

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

In the above example, we use a BufferedReader to read the file line by line. We create an instance of FileReader by providing the file path and pass it to the BufferedReader constructor. Inside the try block, we read each line using readLine() method until it returns null, indicating the end of the file. The IOException is caught in case there is an error while reading the file.

  • Writing to a File:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriteExample {
    public static void main(String[] args) {
        String fileName = "path/to/file.txt";
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
            writer.write("Hello, World!");
            writer.newLine();
            writer.write("This is a sample text.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, we use a BufferedWriter to write data to a file. We create an instance of FileWriter by providing the file path and pass it to the BufferedWriter constructor. Inside the try block, we use the write() method to write data to the file. The newLine() method is used to insert a newline character. The IOException is caught in case there is an error while writing to the file.

Remember to replace "path/to/file.txt" with the actual file path you want to read from or write to. Additionally, it’s important to handle any exceptions that might occur during file operations using try-catch blocks to ensure proper error handling and resource cleanup.

Copyright ©TechOceanhub All Rights Reserved.