为什么我正在创建的文本文件中缺少最后几行?
我有一个函数可以创建 7 个不同的文本文件,其中包含数据行。然后使用以下函数将这 7 个文件组合成不同函数中的单个文件:
public void createSingle683File(int groupNumber, FileWriter wr){
try{
if(new File(printDir+"683_"+groupNumber+".txt").exists()){
File f683 = new File(printDir+"683_"+groupNumber+".txt");
BufferedReader input = new BufferedReader(new FileReader(f683));
String line = null;
while ((line = input.readLine()) != null){
//write contents of existing file to new file
wr.write(line+"\n");
}
//close bufferedInput
input.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
调用代码:
File fileHandle683 = new File(printDir+"683.txt");
FileWriter wr683 = new FileWriter(fileHandle683);
for (int groupNumber = 1; groupNumber < 8; groupNumber++){
createSingle683File(groupNumber,wr683);
}
.
.
.
.
.//stuff
wr683.close();
最后的 683.txt 从第 7 个文件 (683_7.txt) 中丢失了大约 50 行,我无法弄清楚为什么。最终文件的最后几行始终缺失。我不知道我是否很快就会关闭 bufferInput 或者什么。
任何想法将不胜感激。我可以很快地测试任何想法。
谢谢!
I have a function that creates 7 different text files with rows of data. Those 7 files are then combined into a single file in a different function using the following function:
public void createSingle683File(int groupNumber, FileWriter wr){
try{
if(new File(printDir+"683_"+groupNumber+".txt").exists()){
File f683 = new File(printDir+"683_"+groupNumber+".txt");
BufferedReader input = new BufferedReader(new FileReader(f683));
String line = null;
while ((line = input.readLine()) != null){
//write contents of existing file to new file
wr.write(line+"\n");
}
//close bufferedInput
input.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
The calling code:
File fileHandle683 = new File(printDir+"683.txt");
FileWriter wr683 = new FileWriter(fileHandle683);
for (int groupNumber = 1; groupNumber < 8; groupNumber++){
createSingle683File(groupNumber,wr683);
}
.
.
.
.
.//stuff
wr683.close();
Alaways the final 683.txt is missing about 50 lines from the 7th file (683_7.txt) and I can't figure out why. It's always, and only, the last few lines of the final file that are missing. I can't tell if I am closing the bufferInput to soon or what.
Any ideas would be greatly appreciated. I can test any ideas really quickly.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否在该 FileWriter 实例上调用
flush()
和/或close()
?Are you calling
flush()
and/orclose()
on that FileWriter instance?我不明白你在哪里关闭
wr683
。我怀疑当进程关闭时数据被留在缓冲区中。至少调用flush()
。I don't see where you are closing
wr683
. I suspect that the data is being left in a buffer when the process shuts down. At least callflush()
.目前您没有关闭最终文件的文件编写器。因此,当前丢失的内容可能仍在流 I/O 的缓存中。因此关闭最终文件的FileWriter实例并查看文件的内容。
所以在 for 循环之后你只需输入
希望有帮助。
Currently you are not closing the file writer for the final file. So it may be, that the contents you are missing currently are still in the cache of the stream I/O. So close the FileWriter instance of the final file and look at the contents of the file.
So after the for loop you simply enter
Hope it helps.