为什么 myfile.txt 为空?我尝试将内容附加到 myfile.txt 但当我打开它时它仍然是空的。正在创建文件。
import java.io.*;
public class NewClass1 {
@SuppressWarnings("empty-statement")
public static void main(String[] args) throws IOException{
File inputFile = new File("input.txt");
FileReader in1=null;
in1 = new FileReader("input.txt");
char c;
int count=0;
int r;
String s="";
File file;
file = new File("myfile.txt");
file.createNewFile();
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
while((r=in1.read())!=-1) {
c = (char)r;
s=s+c;
if (c == '1' ) {
count++;
}
if (c == '\n') {
if (count>1) {
out.print(s);
}
s = "";
count=0;
}
}
}
}
最佳答案
您必须刷新并关闭输出文件,才能将最后一个充满字符的缓冲区实际保存到磁盘。
out.flush();
out.close();
BufferedWriter的目的是将这些字符保存在内存缓冲区中,直到刷新缓冲区为止。
调用“close”也应该刷新,因此调用它也应该导致缓冲区被写入。
还有其他可能的原因:我假设您已检查 input.txt 不为空,并且其中至少有一个换行符 (\n)。该算法仅在看到换行符时才会写入,如果不存在换行符,则不会写入任何内容。
最后,我不建议使用“FileWriter”,因为字符编码取决于您的操作环境,而该环境可能会发生变化。最好使用 OutputStreamWriter 和 FileOutputStream 指定“UTF-8”(或其他特定字符编码)。
关于java - myfile.txt 中不存在任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23252506/