Alex Rivera | Logout

How do I create a file and write to it?

Asked 2010-05-21T19:58:55.167
1551

What's the simplest way to create and write to a (text) file in Java?

Edit
Report

1 Answer

40

Use:

try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("myFile.txt"), StandardCharsets.UTF_8))) {
    writer.write("text to write");
} 
catch (IOException ex) {
    // Handle me
}  

Using try() will close stream automatically. This version is short, fast (buffered) and enables choosing encoding.

This feature was introduced in Java 7.

answered 2013-04-19T14:35:30.013

Your Answer