Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In Java, I have text from a text field in a String variable called "text".

How can I save the contents of the "text" variable to a file?

like image 214
Justin White Avatar asked Jun 27 '09 19:06

Justin White


People also ask

Can we convert string to file in Java?

In this example, we shall use Apache's commons.io package to write string to file. Create file object with the path to the text file. Have your data ready in a string. Call the method FileUtils.


2 Answers

If you're simply outputting text, rather than any binary data, the following will work:

PrintWriter out = new PrintWriter("filename.txt"); 

Then, write your String to it, just like you would to any output stream:

out.println(text); 

You'll need exception handling, as ever. Be sure to call out.close() when you've finished writing.

If you are using Java 7 or later, you can use the "try-with-resources statement" which will automatically close your PrintStream when you are done with it (ie exit the block) like so:

try (PrintWriter out = new PrintWriter("filename.txt")) {     out.println(text); } 

You will still need to explicitly throw the java.io.FileNotFoundException as before.

like image 121
Jeremy Smyth Avatar answered Oct 06 '22 10:10

Jeremy Smyth


Apache Commons IO contains some great methods for doing this, in particular FileUtils contains the following method:

static void writeStringToFile(File file, String data)  

which allows you to write text to a file in one method call:

FileUtils.writeStringToFile(new File("test.txt"), "Hello File"); 

You might also want to consider specifying the encoding for the file as well.

like image 31
Jon Avatar answered Oct 06 '22 09:10

Jon