Organizational Research By

Surprising Reserch Topic

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


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


asked Jun 18, 2015 in Core java by rajesh
0 votes
73 views



Related Hot Questions

3 Answers

0 votes

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.

Edit: further simplified per Jonik's comments.

answered Jun 18, 2015 by rajesh
0 votes

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.

answered Jun 18, 2015 by rajesh
0 votes

Just did something similar in my project. Use FileWriter will simplify part of your job. And here you can find nice tutorial.

BufferedWriter writer = null;
try
{
    writer = new BufferedWriter( new FileWriter( yourfilename));
    writer.write( yourstring);

}
catch ( IOException e)
{
}
finally
{
    try
    {
        if ( writer != null)
        writer.close( );
    }
    catch ( IOException e)
    {
    }
}
answered Jun 18, 2015 by rajesh

...