I have a String that is storing the processed results for a few files. How do I write that String to a .txt file in my project? I have another String variable which is the desired name of the .txt file.
-
2What have you searched for before asking this question? – bluesman Apr 30 '12 at 20:38
-
1Any code sample you already tried and it didn't work? – Eugene Retunsky Apr 30 '12 at 20:39
-
1possible duplicate of [How do I save a String to a text file using Java?](http://stackoverflow.com/questions/1053467/how-do-i-save-a-string-to-a-text-file-using-java) – Rob Hruska Apr 30 '12 at 20:40
-
1You could try using a FileWriter: http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html – jahroy Apr 30 '12 at 20:42
3 Answers
Try this:
//Put this at the top of the file:
import java.io.*;
import java.util.*;
BufferedWriter out = new BufferedWriter(new FileWriter("test.txt"));
//Add this to write a string to a file
//
try {
out.write("aString\nthis is a\nttest"); //Replace with the string
//you are trying to write
}
catch (IOException e)
{
System.out.println("Exception ");
}
finally
{
out.close();
}

- 4,068
- 1
- 20
- 23
-
1Better specify your encoding: try(BufferedWriter out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(path), StandardCharsets.UTF_8 ));) { out.write(content); } – pdem May 14 '18 at 14:09
Do you mean like?
FileUtils.writeFile(new File(filename), textToWrite);
FileUtils is available in Commons IO.

- 525,659
- 79
- 751
- 1,130
-
1Although it is an old thread - which source is the FileUtils you are referring to? – jamesdeath123 Mar 04 '17 at 23:05
-
Files that are created using byte-based streams represent data in binary format. Files created using character-based streams represent data as sequences of characters. Text files can be read by text editors, whereas binary files are read by a program that converts the data to a human-readable format.
Classes FileReader
and FileWriter
perform character-based file I/O.
If you are using Java 7, you can uses try-with-resources
to shorten method considerably:
import java.io.PrintWriter;
public class Main {
public static void main(String[] args) throws Exception {
String str = "写字符串到文件"; // Chinese-character string
try (PrintWriter out = new PrintWriter("output.txt", "UTF-8")) {
out.write(str);
}
}
}
You can use Java’s try-with-resources
statement to automatically close resources (objects that must be closed when they are no longer needed). You should consider a resource class must implement the java.lang.AutoCloseable
interface or its java.lang.Closeable
subinterface.

- 41,222
- 15
- 102
- 148