If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To read and write data in a file in Java, you can use various classes from the java.io
package. Specifically, FileReader
, FileWriter
, BufferedReader
, and BufferedWriter
are commonly used for character-based file reading and writing.
Here's an example of how to read data from an existing file and write data to a new file:
javaCopy codeimport java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReadWriteExample {
public static void main(String[] args) {
String inputFile = "input.txt";
String outputFile = "output.txt";
// Step 1: Read data from the input file
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Read: " + line);
}
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
e.printStackTrace();
}
// Step 2: Write data to the output file
try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
writer.write("Hello, this is the first line.\n");
writer.write("Writing data to a file in Java.");
System.out.println("Data written to the file successfully.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
}
}
}
In this example, we have two steps:
Reading from the input file ("input.txt"):
BufferedReader
to read line by line from the file.readLine()
method returns each line as a String
until the end of the file is reached.Writing to the output file ("output.txt"):
BufferedWriter
to write data to the file.write()
method is used to write data, and \n
is used to add a new line.Remember to handle exceptions properly and close the resources using try-with-resources for efficient and safe file handling.
Before running the code, create an "input.txt" file in the same directory as the Java program and add some text to it. The program will read the content of the "input.txt" file and display it on the console. It will also write some data to a new file named "output.txt".
Under Section 107 of the copyright act 1976, allowance is made for fair use for purposes such as criticism, comment, news reporting, scholarship, and research. Fair use is a use permitted by copyright statute that might otherwise be infringing. Non-profit, educational, or personal use tips the balance in favor of fair use.
Comments: 0