如果没有先关闭我的BufferedWriter,我如何访问文件中的数据?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Tp {
public static void main(String[] args) throws IOException{
File f = new File("Store.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
BufferedReader br = new BufferedReader(new FileReader(f));
bw.write("Some text");
System.out.println(br.readLine());
bw.write("Some more text");
bw.close();
br.close();
}
}
控制台显示为null。我该如何解决这个问题?
答案 0 :(得分:3)
你还没有刷新流
public class Tp {
public static void main(String[] args) throws IOException{
File f = new File("/path/to/your/file/filename.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
BufferedReader br = new BufferedReader(new FileReader(f));
bw.write("Some text");
bw.flush();
System.out.println(br.readLine());
bw.write("Some more text");
bw.flush();
bw.close();
br.close();
}
}