在下面的程序中,循环迭代1000次,我使用FileWriter在文件中写入所有条目,但不幸的是程序最终只在文件中写入510(有时是415,有时是692,总是少于1000)条目,但循环迭代1000次.
import java.io.* ;
import java.util.*;
public class DemoWriter {
public static void main(String[] args) throws Exception {
List<String> receiverList = new ArrayList<String>() ;
receiverList.add("abc@gmail.com") ;
receiverList.add("pqr@ibibo.com") ;
receiverList.add("xyz@gmail.com") ;
FileWriter fw = new FileWriter("a.txt") ;
BufferedWriter bw = new BufferedWriter(fw) ;
int size = receiverList.size() ;
String str ;
int count = 0 ;
for(int i = 1 ; i <= 1000 ; ++i){
str = receiverList.get( (int) (Math.random() * size) ) + "\n" ;
bw.write(++count + ".> " + str) ;
System.out.print(count + ".> " + str) ;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是因为文件大小或其他原因???
Thnx对这里所有好人的快速反应.我已经纠正了我的代码(我只是忘了关闭流,现在代码工作完美).正如所有人都指出我需要关闭流,但我接受BalusC,因为他是第一个回复的人.
很高兴来到这里的BalusC.干杯:)
你没有关闭和冲洗你的作家.如果close()在代码末尾调用编写器上的方法,则刷新缓冲区并关闭编写器.
正如Hank Gay在评论中指出的那样,这些close()方法可能会引发异常(IOException我相信).这意味着你必须将调用封装在try/ catchblock中.但是,我看到你的main方法抛出Exception- 这不是最好的做法,但它会阻止你在这个特定的实例中需要try/ catchblock.
实际上,您应该始终关闭资源以清除所有内容并释放资源.没有必要明确刷新,因为它通常在结束时隐式完成.只需在try-catch-finally块的finally块中调用Closeable#close(),你就可以了.
在Java IO教程中了解更多信息.
| 归档时间: |
|
| 查看次数: |
497 次 |
| 最近记录: |