为什么缓冲区写入者不写入文件? [英] why is bufferedwriter not writing in the file?
问题描述
以下是代码段。
read = new FileReader("trainfiles/"+filenames[i]);
br = new BufferedReader(read);
while((lines = br.readLine())!=null){
st = new StringTokenizer(lines);
while(st.hasMoreTokens()){
bw = new BufferedWriter(new FileWriter("files/file.txt"));
bw.write(st.nextToken());
bw.newLine();
}
}
编辑:
我正在读取文件一个目录。所以,我需要在每个循环中打开阅读器。我做了一些修改,但后来也没有写入该文件。
这是代码:
I am reading files from a directory. So, I need to open the reader in every loop. I have made some modification, but then also it is not writing to that file. Here is the code:
for(i=0;i==0;i++){
if(filenames[i].matches(".*ham.*")){
System.out.println("ham:"+filenames[i]);
read = new FileReader("trainfiles/"+filenames[i]);
br = new BufferedReader(read);
while((lines = br.readLine())!=null){
st = new StringTokenizer(lines);
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
bw.write(st.nextToken());
}
}
bw.close();
br.close();
}else{
System.out.println("spam:"+filenames[i]);
}
}
编辑:
我修改了代码,但没有成功,
edit: I modified the code, but no success,
while((lines = br.readLine())!=null){
st = new StringTokenizer(lines);
bw = new BufferedWriter(new FileWriter("files/file.txt"));
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
bw.write(st.nextToken());
}
bw.close();
}
br.close();
我收到此错误:线程mainjava中的异常。 util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:332)
at Test.main(Test.java:30)
编辑:
谢谢大家......我想通了。实际上我在eclipse中创建了一个目录,但我没有刷新它以查看内容。愚蠢......反正。谢谢很多
edit: Thanks guys.. I figured it out. Actually I created an directory in eclipse and I did not refresh it to see the content. Its silly... anyways.thanks a lot
推荐答案
- 你正在循环中创建FileWritter所以你总是在每个循环中截断文件。
- 你忘了关闭/刷新写入者
- 但运气好(终止程序可能导致写入器刷新)文件将包含输入文件的最后一个单词,我只能猜测它是一个新行,当你打开文件检查内容时,你可能错过了。
你的内循环应该是这样的:
Your inner loop should be something like this:
try (BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt"))) {
while (st.hasMoreTokens()) {
bw.write(st.nextToken());
bw.newLine();
}
}
这篇关于为什么缓冲区写入者不写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!