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
🌐
W3Schools
w3schools.com › java › java_files_write.asp
Java Write To Files
Java Examples Java Videos Java ... you are just starting with Java, the easiest way to write text to a file is by using the FileWriter class....
🌐
GeeksforGeeks
geeksforgeeks.org › java › writer-writestring-method-in-java-with-examples
Writer write(String) method in Java with Examples - GeeksforGeeks
October 24, 2025 - import java.io.*; class GFG{ public static void main(String[] args){ try { // Create a Writer instance that writes to console Writer writer = new PrintWriter(System.out); // Write the String 'GFG' to the stream writer.write("GFG"); // Flush the stream to ensure data is printed writer.flush(); } catch (Exception e) { System.out.println(e); } } }
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).

🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › io › Writer.html
Writer (Java Platform SE 8 )
April 21, 2026 - 8 ... BufferedWriter, CharArrayWriter, ... class for writing to character streams. The only methods that a subclass must implement are write(char[], int, int), flush(), and close()....
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-write-into-a-file
Java Program to Write into a File - GeeksforGeeks
July 23, 2025 - FileWriter class in Java is used to write character-oriented data to a file as this class is character-oriented because it is used in file handling in Java.
🌐
Programiz
programiz.com › java-programming › writer
Java Writer (With Example)
write(String data) - writes the specified string to the writer · append(char c) - inserts the specified character to the current writer
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-write-to-file
Java Write to File - 4 Ways to Write File in Java | DigitalOcean
August 3, 2022 - Let’s have a brief look at four options we have for java write to file operation. FileWriter: FileWriter is the simplest way to write a file in Java. It provides overloaded write method to write int, byte array, and String to the File. You can also write part of the String or byte array using ...
🌐
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.
Find elsewhere
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › io › Writer.html
Writer (Java Platform SE 7 )
7 ... BufferedWriter, CharArrayWriter, ... class for writing to character streams. The only methods that a subclass must implement are write(char[], int, int), flush(), and close()....
🌐
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.
🌐
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 ...
🌐
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 = "\nJava files are easy"; try { BufferedWriter writer = new BufferedWriter(new FileWriter("newfile.txt", true)); writer.write(stringToWrite); writer.close(); } catch (IOException ioe) { System.out.println("Couldn't write to file"); } } } The code above will append a new line saying “Java files are easy” to the newfile.txt each time it is run. ... Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski. SEE EPISODES · How do I generate random integers within a specific range in Java?
🌐
How to do in Java
howtodoinjava.com › home › i/o › java write to file: clean code vs. performance
Java Write to File: Clean Code vs. Performance
October 12, 2023 - DataOutputStream lets an application write primitive Java data types to an output stream in a portable way.
🌐
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.
🌐
Tutorialspoint
tutorialspoint.com › java › java_write_file.htm
Java - Writing to File
FileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn't already exist, before opening it for output. Here are two constructors which can be used to create a FileOutputStream object.
🌐
Oracle
docs.oracle.com › en › java › javase › 17 › docs › api › java.base › java › io › Writer.html
Writer (Java SE 17 & JDK 17)
April 21, 2026 - Writes a portion of a string. clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait ... The object used to synchronize operations on this stream. For efficiency, a character-stream object may use an object other than itself to protect critical sections.
🌐
YouTube
youtube.com › watch
How to WRITE FILES with Java in 8 minutes! ✍ - YouTube
#java #javatutorial #javacourse import java.io.FileNotFoundException;import java.io.FileWriter;import java.io.IOException;public class Main { public stati...
Published   December 12, 2024
🌐
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.
🌐
Scaler
scaler.com › home › topics › java › java io - write to a file using java io streams
JAVA IO | Write A File Using JAVA IO Streams - Scaler Topics
May 5, 2024 - The .write() method of BufferedWriter class in Java is used to write the text in a character-output stream. Buffering characters efficiently write strings, single characters, and arrays.