Note that each of the code samples below may throw IOException. Try/catch/finally blocks have been omitted for brevity. See this tutorial for information about exception handling.

Note that each of the code samples below will overwrite the file if it already exists

Creating a text file:

PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();

Creating a binary file:

byte data[] = ...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(data);
out.close();

Java 7+ users can use the Files class to write to files:

Creating a text file:

List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, StandardCharsets.UTF_8);
//Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);

Creating a binary file:

byte data[] = ...
Path file = Paths.get("the-file-name");
Files.write(file, data);
//Files.write(file, data, StandardOpenOption.APPEND);
Answer from Michael on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › nio › file › Files.html
Files (Java Platform SE 8 )
April 21, 2026 - The options parameter determines how the file is opened. The READ and WRITE options determine if the file should be opened for reading and/or writing. If neither option (or the APPEND option) is present then the file is opened for reading.
🌐
W3Schools
w3schools.com › java › java_files_write.asp
Java Write To Files
Explanation: This program tries to write some text into a file named filename.txt. If everything works, the program will print "Successfully wrote to the file." in the console. If something goes wrong (for example, the file cannot be opened), it will print "An error occurred." instead. Since Java 7, you can use try-with-resources.
🌐
Medium
medium.com › @AlexanderObregon › javas-files-write-method-explained-288e75dfc721
Java’s Files.write() Method Explained | Medium
March 20, 2025 - The Files.write() method, introduced as part of the New I/O (NIO.2) API in Java 7, revolutionized file I/O operations in Java. It provides a simple and efficient way to write data to files, catering to the needs of modern Java applications.
🌐
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.
Top answer
1 of 16
1877

Note that each of the code samples below may throw IOException. Try/catch/finally blocks have been omitted for brevity. See this tutorial for information about exception handling.

Note that each of the code samples below will overwrite the file if it already exists

Creating a text file:

PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();

Creating a binary file:

byte data[] = ...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(data);
out.close();

Java 7+ users can use the Files class to write to files:

Creating a text file:

List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, StandardCharsets.UTF_8);
//Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);

Creating a binary file:

byte data[] = ...
Path file = Paths.get("the-file-name");
Files.write(file, data);
//Files.write(file, data, StandardOpenOption.APPEND);
2 of 16
452

In Java 7 and up:

try (Writer writer = new BufferedWriter(new OutputStreamWriter(
              new FileOutputStream("filename.txt"), "utf-8"))) {
   writer.write("something");
}

There are useful utilities for that though:

  • FileUtils.writeStringtoFile(..) from commons-io
  • Files.write(..) from guava

Note also that you can use a FileWriter, but it uses the default encoding, which is often a bad idea - it's best to specify the encoding explicitly.

Below is the original, prior-to-Java 7 answer


Writer writer = null;

try {
    writer = new BufferedWriter(new OutputStreamWriter(
          new FileOutputStream("filename.txt"), "utf-8"));
    writer.write("Something");
} catch (IOException ex) {
    // Report
} finally {
   try {writer.close();} catch (Exception ex) {/*ignore*/}
}

See also: Reading, Writing, and Creating Files (includes NIO2).

🌐
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 example, a FileWriter object is created for the file “output.txt”, and the write() method is used to write the string “Hello, world!” to the file. IOExceptions are handled to ensure proper error management during file operations. ... The NIO API, introduced in Java 1.4, provides enhanced I/O capabilities, especially for handling large volumes of data.
Find elsewhere
🌐
Codefinity
codefinity.com › courses › v2 › 50afb341-f062-4e2b-8869-119864e9e490 › bb705a9c-4b98-4165-aaee-37bf1ae1e98d › 03101271-5eb5-487e-99fd-084a0d9904d3
Learn Creating and Writing to a File | Java File I/O Essentials
To improve performance, you can wrap a FileWriter with a BufferedWriter, which collects output in a buffer and writes larger chunks at once. This makes your file operations more efficient, especially when writing many lines of text. ... 12345678910111213141516171819202122232425262728 import java.io.FileWriter; import java.io.BufferedWriter; import java.io.IOException; public class WriteToFileExample { public static void main(String[] args) { String filename = "output.txt"; try { // Create a FileWriter wrapped with a BufferedWriter BufferedWriter writer = new BufferedWriter(new FileWriter(filen
🌐
DataCamp
datacamp.com › doc › java › create-&-write-files
Java Create & Write Files
Learn how to efficiently create and write files in Java using classes like File, FileWriter, and BufferedWriter. Follow best practices for error handling and resource management.
🌐
Mkyong
mkyong.com › home › java › java create and write to a file
Java create and write to a file - Mkyong.com
October 2, 2020 - In Java, we can use Files.write to create and write to a file.
🌐
CodeGym
codegym.cc › java blog › java io & nio › java – write to file
Java – Write to File
December 26, 2024 - We then create a FileChannel object named channel, which is initialized using randomAccessFile object. We then create a ByteBuffer object named buffer with a capacity of 1024 bytes and put the textToWrite string as the parameter. We then flip the buffer object to prepare it for writing and write it to the channel object using the write() method. Finally, we close the randomAccessFile object. Java provides the Files class in the java.nio.file package, which includes methods to create and manage temporary files easily.
🌐
W3Schools
w3schools.com › java › java_files_create.asp
Java Create Files
In Java, you can create a new file with the createNewFile() method from the File class.
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › io › file.html
Reading, Writing, and Creating Files (The Java™ Tutorials > Essential Java Classes > Basic I/O)
Specifying READ opens the channel for reading. Specifying WRITE or APPEND opens the channel for writing. If none of these options are specified, then the channel is opened for reading. The following code snippet reads a file and prints it to standard output:
🌐
GeeksforGeeks
geeksforgeeks.org › java › filewriter-class-in-java
Java FileWriter Class - GeeksforGeeks
November 4, 2025 - import java.io.*; class AppendingFile { public static void main (String[] args) { String fileName = "output.txt"; // Appending Data in the File try (FileWriter writer = new FileWriter(fileName, true)) { // true for append mode writer.write("\nAppending this line to the file."); System.out.println("Data appended to the file successfully."); } catch (IOException e) { System.out.println("An error occurred while appending" + " to the file: " + e.getMessage()); } } }
🌐
Sentry
sentry.io › sentry answers › java › how to write to a file in java
How to Write to a File in Java | Sentry
The FileWriter class has been around since Java 1.1, and it’s a convenient class for writing character-oriented files. The syntax for FileWriter is concise and intuitive. An advantage of using the FileWriter class is that it has a boolean ...
🌐
Baeldung
baeldung.com › home › java › java io › java – create a file
Java - Create a File | Baeldung
August 29, 2024 - In this quick tutorial, we’re going to learn how to create a new File in Java – first using the Files and Path classes from NIO, then the Java File and FileOutputStream classes, Google Guava, and finally the Apache Commons IO library.
🌐
Hyperskill
hyperskill.org › university › java › writing-files-in-java
Writing Files in Java
December 3, 2024 - File file = new File("/home/username/path/to/your/file.txt"); FileWriter writer = new FileWriter(file, true); // appends text to the file writer.write("Hello, World\n"); writer.close(); This code appends a new line to the file. Run it multiple times to see what happens.
🌐
Java Guides
javaguides.net › 2019 › 07 › java-write-file-with-fileswrite-api.html
Java Files write() Method Example
June 21, 2024 - The Files.write() method takes a Path object and a sequence of bytes or a list of strings as arguments. import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.io.IOException; import java.util.List; import ...
🌐
Sentry
sentry.io › sentry answers › java › how to create a file and write to it in java
How to create a file and write to it in Java | Sentry
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class Main { public static void main(String[] args) { String stringToWrite = "Java files are easy"; try { BufferedWriter writer = new BufferedWriter(new FileWriter("newfile.txt")); writer.write(stringToWrite); writer.close(); } catch (IOException ioe) { System.out.println("Couldn't write to file"); } } }
🌐
TMSVR
tmsvr.com › java-file-writing-i-o-performance
Java File writing I/O performance
February 13, 2026 - For durable commit logs → Use RandomAccessFile with sync() or a batched FileChannel.force(false). For ultra-fast writes → Use MappedByteBuffer, though durability isn’t guaranteed. Understanding how Java handles buffering and durability ensures optimal performance without unnecessary disk I/O.