Java中的缓冲Writer无法正确写入

时间:2013-09-27 00:23:27

标签: java bufferedwriter

我正在制作一个madlib程序,打开一个txt文件,然后询问用户数据,然后呈现最终的madlib,它在控制台中完美显示,但只有madlib的最后一行出现在文本文件中请在Java中帮助这个btw

FileWriter outFile = new FileWriter(name + ".txt");
BufferedWriter bf = new BufferedWriter(outFile);

long start = System.nanoTime();    
content = JOptionPane.showInputDialog("Please enter a/n " + 
       m.group().subSequence(1,m.group().length()-1));

madlib = m.replaceFirst(content);
System.out.println(madlib);
bf.write(madlib);

long elapsedTime = System.nanoTime() - start;
elapsedTime=elapsedTime/1000000;
System.out.println(m.group().subSequence(1,m.group().length()-1) + " ; " + 
       content + " ; " + elapsedTime +"ms");
bf.write(m.group().subSequence(1,m.group().length()-1) + " ; " + content + 
       " ; " + elapsedTime +"ms");
bf.close();

3 个答案:

答案 0 :(得分:1)

我猜你的代码嵌套在while循环中,特别是考虑到你使用m.group(),如果是这样的话,你在循环内部得到了太多,因为你每个都在创建一个新的BufferedWriter循环时间循环,从而覆盖之前写入的所有内容。

解决方案:在循环之前创建BufferedWriter ,使用它进行写入,在循环内部,然后在循环结束后将其关闭。像(伪代码)的东西:

Create FileWriter
Create BufferedWriter with FileWriter
Start your while loop and loop through your groups
  Do your loops, get your user's input
  Write out the users input using the BufferedWriter
end while loop
Close the BufferedWriter (preferably done in a finally block).

顺便说一句,下次,在您的问题中包含所有相关信息,包括您使用循环。我们有时会猜测未显示的代码或未提供的信息。

答案 1 :(得分:1)

根据提供的信息,我只能建议以追加模式打开文件。

Insted of:

FileWriter outFile = new FileWriter(name + ".txt");

使用:

FileWriter outFile = new FileWriter(name + ".txt", true);

答案 2 :(得分:0)

这段代码只写一行,实际上甚至不是,只是一个没有行终止符的字符串。它将其写入每次执行此代码时新创建的文件。对于您期望文件中会有更多数据没有任何依据。

您可能打算以'append'模式打开文件,或者在关闭之前保持文件打开并多次写入。