Advertisement
Advertisement


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


Question

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?

2014/07/01
1
711
7/1/2014 6:12:07 AM


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.

2012/08/09

Take a look at the Java File API

a quick example:

try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
    out.print(text);
}
2014/03/11

In Java 7 you can do this:

String content = "Hello File!";
String path = "C:/a.txt";
Files.write( Paths.get(path), content.getBytes());

There is more info here: http://www.drdobbs.com/jvm/java-se-7-new-file-io/231600403

2019/10/12

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)
    {
    }
}
2013/07/23

Use FileUtils.writeStringToFile() from Apache Commons IO. No need to reinvent this particular wheel.

2013/06/14

Source: https://stackoverflow.com/questions/1053467
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]