java.io FileReader and FileWriter are character-based classes used in Java to read and write text files. They are ideal for handling plain text data such as logs, configuration files, and reports.
// Writing text to a file using FileWriter
import java.io.FileWriter;
import java.io.IOException;
public class WriteExample {
public static void main(String[] args) throws IOException {
FileWriter writer = new FileWriter("data.txt");
writer.write("Hello Java FileWriter");
writer.close();
}
}
// Reading text from a file using FileReader
import java.io.FileReader;
import java.io.IOException;
public class ReadExample {
public static void main(String[] args) throws IOException {
FileReader reader = new FileReader("data.txt");
int ch;
while ((ch = reader.read()) != -1) {
System.out.print((char) ch);
}
reader.close();
}
}
The first program creates a file named data.txt and writes text into it. The second program reads the file character by character and prints the content to the console.
Test the concepts! Enter text below to "Write" it to a virtual data.txt file, then click "Read" to display it in the console.