tags:

views:

56

answers:

4

Hi guys,

i have the following class that writes to a file but is not working as i want. I call the write method in a while loop so that it writes a string to a new line. It only writes the last string. All the previous ones are not written except the last one.

Here is the class:

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Writer {

 private static PrintWriter  outputStream = null;

 public Writer(String algorithmName){
  try {
   outputStream = new PrintWriter(new FileWriter(algorithmName+".txt"));
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
     public  void write(String str){
        try {
                outputStream.append(str);
        }catch(Exception exc){

        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
}

example code:

Writer w = new Writer("filename");
for(int = i; i < 10; i++){
w.write(i);
}

In this case i get as results:

9

instead of

0
1
2
3
...
9

what am i doing wrong?

thanks

+1  A: 

You're closing the output stream after every write operation. You should call it one time after having written everything.

thejh
Thanks for your reply. How do i let each string appear on a separate line? I tried to append "\n" after each string but is not working.
Kap
If it's a Windows system, try `"\r\n"`.
thejh
Thanks soooooo much it works now. thaaanks
Kap
A: 

everytime you write, you are closing the stream which then forces a new file to be created that is why all that is in the file is 9.

Writer output = new BufferedWriter(new FileWriter(algorithmName+".txt"));
try {
  for(int = i; i < 10; i++){
      output.write( i );
  }
}
finally {
  output.close();
}
Aaron Saunders
thanks. i want each string to appear on a separate line. how do i do it?
Kap
A: 

I'll be a bit off topic and recommend the Google Guava library to you, since it contains a lot of useful everyday functionality.

Using it, the solution to your problem becomes almost a one-liner with:

for(int i = 0; i < 10; ++i) {
    Files.append(String.valueOf(i) + "\n", new File("filename"), Charsets.UTF_8);
}

Edit: you shouldn't use this in large loops because the library is probably effectively opening and closing the file every single time. Not efficient at all.

darioo
Thanks but is there not a way to do it with the Java libraries?
Kap
I'm afraid you can't do it much shorter than what you did using just standard Java libraries. To reduce boilerplate code like this, libraries like Google Guava and Apache Commons have been created.
darioo