In this article, you'll learn how to create a new text file and write data into it using Java.

Write to a file using Files.write()

If you are using Java 8 or higher, use Java New I/O API Files.write() static method to create and write to a file. It is much cleaner and easier to use than the legacy I/O API.

Here is an example:

try {
    // data to write
    List<String> contents = Arrays.asList("Hey, there!", "What's up?");

    // write data
    Files.write(Paths.get("output.txt"), contents);

} catch (IOException ex) {
    ex.printStackTrace();
}

The above code will create a new file if it does not exist and write to it after truncating any existing data. If you only want to append data to an existing file, do the following:

Files.write(Paths.get("output.txt"), contents, StandardOpenOption.APPEND);

The above code will through an exception if the file doesn't exist. To avoid the exception, you can combine both create and append modes:

Files.write(Paths.get("output.txt"), contents, StandardOpenOption.CREATE, 
        StandardOpenOption.APPEND);

If you want to specify an encoding scheme other than the default operating system character encoding, do the following:

Files.write(Paths.get("output.txt"), contents, 
        StandardCharsets.UTF_8,
        StandardOpenOption.CREATE);

If you want to write data as bytes, do the following:

byte[] bytes = {65, 66, 67, 68, 69, 70};
Files.write(Paths.get("output.txt"), bytes);

// write 'ABCDEF' to file 

Read how to read and write files using the Java NIO API guide for more examples.

Write to a file using BufferedWriter

You can use the new I/O API (NIO) Files.newBufferedWriter() static method to create a new instance of BufferedWriter. Here is an example:

try {
    // create a writer
    BufferedWriter bw = Files.newBufferedWriter(Paths.get("output.txt"));

    // write text to file
    bw.write("Hey, there!");
    bw.newLine();
    bw.write("What's up?");

    // close the writer
    bw.close();

} catch (IOException ex) {
    ex.printStackTrace();
}

The above code will create a new text file called output.txt with the following contents:

Hey, there!
What's up?

If you want to append data to a file only, do the following while creating BufferedWriter:

BufferedWriter bw = Files.newBufferedWriter(Paths.get("output.txt"), 
        StandardOpenOption.APPEND);

Further Reading

You may be interested in other Java I/O articles:

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.