First, specify the file name and create a File object. Based on that, the character streams "** FileWriter " and " FileReader **" are used to read and write in char units.
By the way, if you use the character stream, the character code is automatically converted, so you can input and output without being aware of the character code of the OS where the file is saved.
The following code creates a file called "text.txt", writes it, and then It is a program that reads the contents of the file and outputs it.
Main.java
import java.io.*;
public class Main {
public static void main(String[] args) {
try (FileWriter text1 = new FileWriter(new File("text.txt"));
FileReader text2 = new FileReader(new File("text.txt"))) {
text1.write("Hello.");
text1.flush();
int i = 0;
while ((i = text2.read()) != -1) {
System.out.print((char) i);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
You are using the ** flush () method ** after the written as "Hello", but this means the process of instruction to perform writing to force the file at the moment of the call.
The previous ** write () method ** requests the write of data, but it is not always written to the file immediately after calling this method. In this program, we want to read and output the first written character, so we command forced writing so that writing is always done before reading.
Also, in the while statement, the ** read () method ** of the FileReader class is used to get the characters written in the file one by one and return them as an int type. The read () method reads one character each time it is executed, and returns -1 when the end of the file is reached, so that condition is included in the judgment statement.
In order to output the int type information acquired by the read () method as a character, an explicit cast to the char type is required, so a cast expression is written and converted to the char type.
You can read and write files by doing this.
Next time, I would like to describe the BufferedReader, BefferedWriter classes, serialization, etc.
Recommended Posts