0
我有以下示例應用程序,我在其中寫入文件並在關閉寫入程序後立即嘗試從文件中讀取,但令我驚訝的是沒有任何內容寫入文件。BufferedWriter在刷新並關閉後不會寫入文件
我已經確認flush()和close()方法在我讀取文件之前被調用,但即使這並不幫助我。
有人能幫我理解爲什麼下面的代碼不工作。
public class TestWrite_Read {
private File file;
private Writer writer;
public TestWrite_Read() {
file = new File("E:\\temp\\test.txt");
try {
writer = new BufferedWriter(new FileWriter(file));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
new TestWrite_Read().write();
new TestWrite_Read().read();
}
private void read() throws Exception {
BufferedReader reader = new BufferedReader(new FileReader(file));
System.out.println("reader.readLine() = " + reader.readLine());
reader.close();
}
private void write() throws Exception {
writer.write(String.valueOf(104));
writer.flush();
writer.close();
}}