这是代码片段。
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();
}
}
编辑:我正在从目录中读取文件。所以,我需要在每个循环中打开阅读器。我做了一些修改,但它也没有写入该文件。这是代码:
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]);
}
}
编辑:我修改了代码,但没有成功,
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();
我收到了这个错误:Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:332)
at Test.main(Test.java:30)
编辑:谢谢大家..我想通了。实际上我在eclipse中创建了一个目录,我没有刷新它来查看内容。它很愚蠢......无论如何。非常感谢