why is bufferedwriter not writing in the file?
Asked Answered
M

3

9

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

Monochromat answered 13/12, 2010 at 15:4 Comment(3)
Is there an error message? Is a file created? Are you calling close()?Leifleifer
Why do you instantiate a new BufferedWriter for every write you do? Besides, you should always close all open streams (after the work is done, ofc :-)).Ignitron
After your last edit you're still creating the BufferedWritter inside the loop. This will truncate your fileVitrine
V
15
  • You are creating the FileWritter inside the loop so you will always truncate the file in each cycle.
  • You forgot to close / flush the writter
  • But with some luck (terminating the program may cause the writter to flush) the file would contain the last word of your input file which I can only guess would be a new line and you probably missed when you opened up the file to check the content.

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();
    }
}
Vitrine answered 13/12, 2010 at 15:17 Comment(3)
The code is not complete, for instance I didn't declared the Tokenizer which looks like is causing the exception. It's just a sample to guide you :)Vitrine
bw.close() is very important. Thanks for suggestion.Olenta
bw.close() will not be called in case of some IOException in the code snippet you've provided. Please, consider using try-with-resources construct in your answer.Forney
B
20

A couple of things:

  1. You're creating a new FileWriter each time through the loop, which will truncate the file each time.
  2. BufferedWriter is buffered, and you're never flushing the buffer. You need to either call bw.flush(), or even better, close the writer when done.
Brote answered 13/12, 2010 at 15:8 Comment(2)
Better, flush the decorator in the happy case. Close the underlying resource in finally. (ObFileWriterComment: FileWriter picks up the character encoding that happens to be the "default" at the time. Much better to explicitly choose an encoding, which means shunning FileWriter (use OutputStreamWriter).)Drucilla
closing provides an implicit flush, so in most simple code closing in a finally is sufficient.Brote
V
15
  • You are creating the FileWritter inside the loop so you will always truncate the file in each cycle.
  • You forgot to close / flush the writter
  • But with some luck (terminating the program may cause the writter to flush) the file would contain the last word of your input file which I can only guess would be a new line and you probably missed when you opened up the file to check the content.

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();
    }
}
Vitrine answered 13/12, 2010 at 15:17 Comment(3)
The code is not complete, for instance I didn't declared the Tokenizer which looks like is causing the exception. It's just a sample to guide you :)Vitrine
bw.close() is very important. Thanks for suggestion.Olenta
bw.close() will not be called in case of some IOException in the code snippet you've provided. Please, consider using try-with-resources construct in your answer.Forney
C
1

Ideally you should use following Constructor to create FileWriter,

bw = new BufferedWriter(new FileWriter("files/file.txt",true));

Second parameter, true is for appending the new data. FileWriter will not truncate your previous write.

and your reader will be able to read proper data.

Cedillo answered 4/5, 2014 at 6:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.