2017-05-27 105 views
0

这是我的代码。如果我输入3行文本,然后键入“退出”,它将只写入文件的最后一行文件。 我错过了什么? 谢谢。为什么BufferedWriter不会写入文件中的所有行?

`public class WriteFile { 
    public static void writeFile() throws IOException { 
     Scanner sc = new Scanner(System.in); 
     String text; 
     File file = new File("file.txt"); 
     BufferedWriter out = new BufferedWriter(new FileWriter(file)); 
     while (!sc.nextLine().equalsIgnoreCase("exit")) { 
       text = sc.nextLine(); 
       out.write(text); 
       out.newLine(); 

      } 
     sc.close(); 
     out.flush(); 
     out.close(); 
    } 
}` 

回答

1

是的,你应该使用append()方法,写删除最后插入的文本:

public static void writeFile() throws IOException { 
     Scanner sc = new Scanner(System.in); 
     String text = ""; 
     File file = new File("file.txt"); 
     BufferedWriter out = new BufferedWriter(new FileWriter(file)); 
     while (!(text = sc.nextLine()).equalsIgnoreCase("exit")) { 
      out.append(text); 
      out.newLine(); 
     } 
     sc.close(); 
     out.flush(); 
     out.close(); 
    } 
+0

它的工作原理!非常感谢! – Flup

+0

我测试了这段代码,它工作的很好,你为什么说它不是很烦人?你得到的结果是什么?你有错误吗? –

+1

对不起,它工作:) – Flup

相关问题