Write A Program In Java To Perform Read And Write Operations On A Text File

0

Write A Program In Java To Perform Read And Write Operations On A Text File

Write a program in java to perform read and write operations on a text file


Here’s an example program that demonstrates how to perform read and write operations on a text file in Java:


Program
import java.io.*;

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

        // Write to a text file
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"))) {
            writer.write("Hello, world!");
            writer.newLine();
            writer.write("This is a text file.");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Read from a text file
        try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output
Hello, world! This is a text file.

Explanation
In this example, we use the BufferedWriter and FileWriter classes to write to a text file called file.txt. We create an instance of BufferedWriter by passing an instance of FileWriter initialized with the name of the file to its constructor.

We then use the write() method of the BufferedWriter object to write two lines of text to the file. We also use its newLine() method to insert a line break between the two lines.

After writing to the file, we close the BufferedWriter object using its close() method. This is done automatically for us because we used a try-with-resources statement.

Next, we use the BufferedReader and FileReader classes to read from the same text file. We create an instance of BufferedReader by passing an instance of FileReader initialized with the name of the file to its constructor.

We then use a while loop and the readLine() method of the BufferedReader object to read each line from the file until there are no more lines left. Inside the loop, we print out each line using the System.out.println() method.

After reading from the file, we close the BufferedReader object.

❤️ I Hope This Helps You Understand, Click Here To Do More Exercise In Java Programming.

Post a Comment

0Comments
Post a Comment (0)