Here is the code snippet.
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();
}
}
Edit: 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();
And i am getting this error: Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:332)
at Test.main(Test.java:30)
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
Class BufferedWriter. Writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings. The buffer size may be specified, or the default size may be accepted. The default is large enough for most purposes.
Never. BufferedWriter itself just writes to another Writer .
Still, if you want to know if the Writer is closed, you can call writer. flush() , if it throws IOException then it means the Writer is already closed.
Writing to a File: If the file does not exist, it is automatically created. : BufferedWriter « File « Java Tutorial. 11.36. 1.
A couple of things:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With