Files.writeString

In Java 11+, there is a convenient method to write strings. Call java.nio.file.Files.writeString:

Files.writeString(
    Paths.get(file.toURI()),   // Path to file.
    "My string to save",       // String to write.
    StandardCharsets.UTF_8     // Character encoding to use in writing file.
);

We can also customize the writing with:

Files.writeString(Paths.get(file.toURI()), 
                  "My string to save", 
                   StandardCharsets.UTF_8,
                   StandardOpenOption.CREATE,
                   StandardOpenOption.TRUNCATE_EXISTING);

ORIGINAL ANSWER:

There is a one-line solution, using Java nio:

java.nio.file.Files.write(Paths.get(file.toURI()), 
                          "My string to save".getBytes(StandardCharsets.UTF_8),
                          StandardOpenOption.CREATE,
                          StandardOpenOption.TRUNCATE_EXISTING);

I have not benchmarked this solution with the others, but using the built-in implementation for open-write-close file should be fast and the code is quite small.

Answer from Roberto on Stack Overflow
Top answer
1 of 5
64

Files.writeString

In Java 11+, there is a convenient method to write strings. Call java.nio.file.Files.writeString:

Files.writeString(
    Paths.get(file.toURI()),   // Path to file.
    "My string to save",       // String to write.
    StandardCharsets.UTF_8     // Character encoding to use in writing file.
);

We can also customize the writing with:

Files.writeString(Paths.get(file.toURI()), 
                  "My string to save", 
                   StandardCharsets.UTF_8,
                   StandardOpenOption.CREATE,
                   StandardOpenOption.TRUNCATE_EXISTING);

ORIGINAL ANSWER:

There is a one-line solution, using Java nio:

java.nio.file.Files.write(Paths.get(file.toURI()), 
                          "My string to save".getBytes(StandardCharsets.UTF_8),
                          StandardOpenOption.CREATE,
                          StandardOpenOption.TRUNCATE_EXISTING);

I have not benchmarked this solution with the others, but using the built-in implementation for open-write-close file should be fast and the code is quite small.

2 of 5
23

I don't think you will be able to get a strict answer without benchmarking your software. NIO may speed up the application significantly under the right conditions, but it may also make things slower. Here are some points:

  • Do you really need strings? If you store and receive bytes from you database you can avoid string allocation and encoding costs all together.
  • Do you really need rewind and flip? Seems like you are creating a new buffer for every string and just writing it to the channel. (If you go the NIO way, benchmark strategies that reuse the buffers instead of wrapping / discarding, I think they will do better).
  • Keep in mind that wrap and allocateDirect may produce quite different buffers. Benchmark both to grasp the trade-offs. With direct allocation, be sure to reuse the same buffer in order to achieve the best performance.
  • And the most important thing is: Be sure to compare NIO with BufferedOutputStream and/or BufferedWritter approaches (use a intermediate byte[] or char[] buffer with a reasonable size as well). I've seen many, many, many people discovering that NIO is no silver bullet.

If you fancy some bleeding edge... Back to IO Trails for some NIO2 :D.

And here is a interesting benchmark about file copying using different strategies. I know it is a different problem, but I think most of the facts and author conclusions also apply to your problem.

Cheers,

UPDATE 1:

Since @EJP tiped me that direct buffers wouldn't be efficient for this problem, I benchmark it myself and ended up with a nice NIO solution using nemory-mapped files. In my Macbook running OS X Lion this beats BufferedOutputStream by a solid margin. but keep in mind that this might be OS / Hardware / VM specific:

public void writeToFileNIOWay2(File file) throws IOException {
    final int numberOfIterations = 1000000;
    final String messageToWrite = "This is a test üüüüüüööööö";
    final byte[] messageBytes = messageToWrite.
            getBytes(Charset.forName("ISO-8859-1"));
    final long appendSize = numberOfIterations * messageBytes.length;
    final RandomAccessFile raf = new RandomAccessFile(file, "rw");
    raf.seek(raf.length());
    final FileChannel fc = raf.getChannel();
    final MappedByteBuffer mbf = fc.map(FileChannel.MapMode.READ_WRITE, fc.
            position(), appendSize);
    fc.close();
    for (int i = 1; i < numberOfIterations; i++) {
        mbf.put(messageBytes);
    }
} 

I admit that I cheated a little by calculating the total size to append (around 26 MB) beforehand. This may not be possible for several real world scenarios. Still, you can always use a "big enough appending size for the operations and later truncate the file.

UPDATE 2 (2019):

To anyone looking for a modern (as in, Java 11+) solution to the problem, I would follow @DodgyCodeException's advice and use java.nio.file.Files.writeString:

String fileName = "/xyz/test.txt";
String messageToWrite = "My long string";
Files.writeString(Paths.get(fileName), messageToWrite, StandardCharsets.ISO_8859_1);
🌐
Medium
medium.com › @vusal.guliyev.313 › writing-files-with-nio-and-io-in-java-bc60b06a413a
Writing Files with NIO and IO in Java | by Vusal Guliyev | Medium
February 9, 2024 - In this NIO example, the Files.write() method is used to write data to a file. The file path, data to be written (converted to bytes), and options such as CREATE to create the file if it doesn’t exist are specified.
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java › nio › file
Java Nio Write File Example - Java Code Geeks
March 12, 2019 - With this example we are going to demonstrate how to use the Non-blocking I/O API, or NIO.2 API (NIO API) for short, to write data to a file. The examples in this article are compiled and run in a Mac OS unix environment. Please note that Java SE 8 is required to run the code in this article.
🌐
Mkyong
mkyong.com › home › java › java create and write to a file
Java create and write to a file - Mkyong.com
October 2, 2020 - 1.2 The below example uses Files.write to create and write a String to a file. ... package com.mkyong.io.file; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.List; public class FileWrite { private static final String NEW_LINE = System.lineSeparator(); public static void main(String[] args) throws IOException { Path path = Paths.get("/home/mkyong/test/aaa.txt"); writeFile(path, "Hello World 1" + NEW_LINE); } // Java 7 private static void writeFile(Path path, String content) throws IOException { // file does not exist, create and write it // if the file exists, override the content Files.write(path, content.getBytes(StandardCharsets.UTF_8)); // Append mode // if the file exists, append string to the end of file.
🌐
Medium
medium.com › @AlexanderObregon › javas-files-write-method-explained-288e75dfc721
Java’s Files.write() Method Explained | Medium
March 20, 2025 - The Files.write() method from the java.nio.file.Files class makes it easy to write data to files in Java. It works well for anything from small configuration files to large log files.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.nio.filenio.files.write
Files.Write Method (Java.Nio.FileNio) | Microsoft Learn
Write lines of text to a file. [Android.Runtime.Register("write", "(Ljava/nio/file/Path;[B[Ljava/nio/file/OpenOption;)Ljava/nio/file/Path;", "", ApiSince=26)] public static Java.Nio.FileNio.IPath? Write(Java.Nio.FileNio.IPath?
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
Find elsewhere
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-files-nio-files-class
Java Files - java.nio.file.Files Class | DigitalOcean
August 4, 2022 - Java NIO Files class provides write(Path path, byte[] bytes, OpenOption… options) method that writes bytes to a file at specified path. The options parameter specifies how the file is created or opened. If no option is specified then it consider CREATE, TRUNCATE_EXISTING and WRITE options ...
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › nio › file › Files.html
Files (Java Platform SE 7 )
If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0 if it exists.
🌐
Attacomsian
attacomsian.com › blog › java-read-write-files-nio-api
Reading and Writing Files using Java NIO API
December 6, 2019 - To write a text, you can use the Files.write() the static method from the NIO API:
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › io › file.html
Reading, Writing, and Creating Files (The Java™ Tutorials > Essential Java Classes > Basic I/O)
Path file = ...; byte[] buf = ...; Files.write(file, buf); The java.nio.file package supports channel I/O, which moves data in buffers, bypassing some of the layers that can bottleneck stream I/O. The newBufferedReader(Path, Charset) method opens a file for reading, returning a BufferedReader ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › read-and-write-files-using-the-new-i-o-nio-2-api-in-java
How to Read and Write Files Using the New I/O (NIO.2) API in Java? - GeeksforGeeks
March 18, 2024 - For writing information into files, we have one class that is Files which is used for handling file operations in NIO. This class is available in java.nio. Then take the information and write it into an example file.
🌐
HowToDoInJava
howtodoinjava.com › home › java 11 › java 11 files.writestring(): writing text to a file
Java 11 Files.writeString(): Writing Text to a File
October 12, 2023 - Java program to write String into a file using Files.writeString() method. import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.Files; import java.io.IOException; import java.nio.file.StandardOpenOption; public class Main ...
🌐
Baeldung
baeldung.com › home › java › java io › java – write to file
Java - Write to File | Baeldung
December 1, 2023 - Looking at the common usage practices, we can see, for example, that PrintWriter is used to write formatted text, FileOutputStream to write binary data, DataOutputStream to write primitive data types, RandomAccessFile to write to a specific position, and FileChannel to write faster in larger files. Some of the APIs of these classes do allow more, but this is a good place to start. This article illustrated the many options of writing data to a file using Java.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › nio › file › Files.html
Files (Java Platform SE 8 )
April 21, 2026 - If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0 if it exists.
🌐
Javapapers
javapapers.com › java › java-nio-file-read-write-with-channels
Java NIO File Read Write with Channels - Javapapers
Path filePath = FileSystems.getDefault().getPath(".", "tempCopy2.txt"); OutputStream outputStream = new BufferedOutputStream( Files.newOutputStream(filePath, StandardOpenOption.CREATE, StandardOpenOption.APPEND)); outputStream.write(byteArray, 0, byteArray.length); Before going into NIO channels lets see a simplistic NIO way to read write files.
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java › io
Java write to File Example - Java Code Geeks
April 14, 2020 - It basically connects a channel of bytes to a file and enables both reading and writing from/to files. You can view it as an alternative to FileOuputStream. A major difference is that a FileChannel connects an allocated byte buffer to the file ...
🌐
Stack Overflow
stackoverflow.com › questions › 11014791 › java-nio-file-channel-writing-to-file
io - Java NIO File Channel writing to file - Stack Overflow
fc.write(buffer, pos); writes bytes to file from beginning, but from pos position in buffer. are you sure that you continuing writing to file?
🌐
Medium
medium.com › @ujjawalr › 7-ways-to-write-files-in-java-from-classic-io-to-modern-nio-549968e0c98d
7 Ways to Write Files in Java — From Classic IO to Modern NIO | by Ujjawal Rohra | Medium
December 25, 2025 - Learn modern Java file writing: 7 effective methods from classic IO to Files.writeString() with real examples and best practices.