我希望通过写入文件来保存状态,然后稍后使用bufferedReader
读取该文件以再次获取状态。这是我的代码:
public static void main(String[] args) throws IOException{
FileWriter fw = new FileWriter("C:\\Users\\Nicolas\\Desktop\\save.txt");
BufferedWriter save = new BufferedWriter(fw);
save.write("helloWorld");
BufferedReader r = new BufferedReader(new FileReader("C:\\Users\\Nicolas\\Desktop\\save.txt"));
System.out.println(r.readLine());
save.close();
}
如果我按下跑步,我打印出null
。我尝试过:
if(r.readLine() != null){
System.out.println(r.readLine());
}
但从逻辑上讲,它现在没有打印出任何东西。我不知道我在这里做错了什么。你能帮帮我吗?
答案 0 :(得分:0)
一个BufferedWriter缓冲区输出,直到您刷新您写入的流,因此您需要通过关闭文件或使用save.flush()
来刷新流。
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("C:\\Users\\Nicolas\\Desktop\\save.txt");
BufferedWriter save = new BufferedWriter(fw);
save.write("helloWorld");
save.flush(); // this writes the bytes in the stream to the file.
BufferedReader r = new BufferedReader(new FileReader("C:\\Users\\Nicolas\\Desktop\\save.txt"));
System.out.println(r.readLine());
save.close();
}
答案 1 :(得分:0)
// Write to file
FileWriter fw = new FileWriter("C:\\Users\\Nicolas\\Desktop\\save.txt");
BufferedWriter save = new BufferedWriter(fw);
save.write("example");
save.flush()
// read as stream
BufferedReader r = new BufferedReader(new FileReader("C:\\Users\\Nicolas\\Desktop\\save.txt"));
System.out.println(r.readLine());
save.close();
答案 2 :(得分:0)
使用BufferedWriter写入文件时,内容不会直接写入磁盘,因为它显然是缓冲的。您应该将内容刷新为@ludo_rj在答案中建议的内容。
最好是尽早关闭作者,这将自动刷新内容。顺便说一句,关闭读者也是必要的。
你应该采用以下机制(我已将方法分配到几种方法中以使其更清晰):
public class SaveStateTesing {
private static final String FILE_NAME = "C:\\Users\\Nicolas\\Desktop\\save.txt";
public static void main(String[] args) throws IOException {
saveState("helloWorld", FILE_NAME);
String state = readState(FILE_NAME);
System.out.println(state);
}
private static void saveState(String state, String fileName) throws IOException {
try(PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(fileName)))) {
writer.println(state);
}
}
private static String readState(String fileName) throws IOException {
try(BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
return reader.readLine();
}
}
}
请注意,我使用了try-with-resource语句,仅在Java 7中可用(当然还有8)。如果您在较旧的Java版本中运行它,则必须按如下方式编写方法:
private static void saveState(String state, String fileName) throws IOException {
PrintWriter writer = null;
try {
writer = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
writer.println(state);
} finally {
if (writer != null)
writer.close();
}
}
private static String readState(String fileName) throws IOException {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(fileName));
return reader.readLine();
} finally {
if (reader != null)
reader.close();
}
}