我花了一个多小时就完成了这项工作,而且我无法在.txt文件中显示任何文字。我做错了什么?
import java.util.*;
import java.io.*;
public class writer {
public static void main(String[] args) {
try {
File txt = new File("myTextFile.txt");
FileWriter fw = null;
fw = new FileWriter(txt);
BufferedWriter edit = null;
edit = new BufferedWriter(fw);
String s = "more text", line = null;
edit.write(s);
Scanner sc = new Scanner(txt);
while (sc.hasNextLine()) {
String i = sc.nextLine();
System.out.println(i);
}
sc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
修改:添加了 .write ,但它仍无效
答案 0 :(得分:2)
您永远不会关闭BufferedWriter
实例,也不会刷新它。所以你永远不要改变流的缓冲区,以便有效地写入物理文件
实际上,您从之前使用的相同源中读取文件。因此,在使用BufferedWriter
阅读内容之前,您必须显式刷新Scanner
的缓冲区:
BufferedWriter edit = new BufferedWriter(fw);
String s = "more text", line = null;
edit.write(s);
edit.flush(); // modification here
Scanner sc = new Scanner(txt);