5

Possible Duplicate:
How do I save a String to a text file using Java?

I want to add a reading from a machine to a file (Java). The reading will be in the form of a string that I have formatted. The file is just a text file. At the moment I am considering Filewriter/Buffered writer is this the correct one to use?

Community
  • 1
  • 1
DavyGravy
  • 311
  • 1
  • 4
  • 14
  • Usually the buffered readers are best but I would advise trying a couple of ways and then timing them. These things often have lots of factors affecting performance – RNJ Oct 30 '12 at 08:40
  • What is a "reading"? Do you just want to write a string to a text file? – Jesper Oct 30 '12 at 08:44

3 Answers3

13

Use FileWriter will do you job.

BufferedWriter writer = new BufferedWriter( new FileWriter( yourfilename));
writer.write( yourstring);
// do stuff 
writer.close();
Sumit Singh
  • 24,095
  • 8
  • 74
  • 100
7

If you are planning to use the JDK alone, you might want to consider wrapping your BufferedWriter with a PrintWriter as in

PrintWriter printWriter=new PrintWriter(bufferedWriter);
printWriter.println(yourString);

The printWriter comes with a nice println method.

Or if you are free to use external libraries, try FileUtils writeStringToFile

Arun Manivannan
  • 4,143
  • 3
  • 27
  • 37
1

Yup. Use java.io.BufferedWriter.

Sumit Singh
  • 24,095
  • 8
  • 74
  • 100
Amit Sharma
  • 5,294
  • 5
  • 24
  • 33