为什么 bufferedwriter 没有写入文件? [英] 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();
我收到此错误:线程main"中的异常 java.util.NoSuchElementException在 java.util.StringTokenizer.nextToken(StringTokenizer.java:332)在 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();
}
}
这篇关于为什么 bufferedwriter 没有写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!