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
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).

🌐
DataCamp
datacamp.com › doc › java › create-&-write-files
Java Create & Write Files
The createNewFile() method is used to create a new file if it does not already exist. import java.io.File; import java.io.IOException; public class CreateFileExample { public static void main(String[] args) { File file = new File("example.txt"); try { if (file.createNewFile()) { System.out...
People also ask

How to write into an existing file in Java?
To write into an existing file, we have to use FileWriter(“fileName”, true) with true as the second parameter.
🌐
intellipaat.com
intellipaat.com › home › blog › how to create and write to files in java?
How to Create and Write to Files in Java? - Intellipaat
How to write String to file in Java?
To write string to file in Java, we have to use some built-in classes like FileWriter, BufferedWriter, or Files.writeString().
🌐
intellipaat.com
intellipaat.com › home › blog › how to create and write to files in java?
How to Create and Write to Files in Java? - Intellipaat
🌐
softwarecave
softwarecave.org › 2021 › 10 › 05 › create-text-file-in-java-with-contents
Create text file in Java with contents | softwarecave
October 5, 2021 - Then subsequent calls to methods print(), printf(), println(), append(), format() or write() populate the contents of the file. Method printf() is especially useful because it provides formatting functionality.
🌐
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.
🌐
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. String content = "..."; Path path = Paths.get("/home/mkyong/test.txt"); // string -> bytes Files.write(path, content.getBytes(StandardCharsets.UTF_8));
🌐
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
This enables append mode, so the file will not be overwritten. 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"); } } }
🌐
Baeldung
baeldung.com › home › java › java io › java – create a file
Java - Create a File | Baeldung
August 29, 2024 - You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence. Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time. ... 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.
Find elsewhere
🌐
Vultr Docs
docs.vultr.com › java › examples › create-file-and-write-to-the-file
Java Program to Create File and Write to the File | Vultr Docs
December 20, 2024 - Import necessary classes from the java.io package. Create FileWriter and BufferedWriter objects, passing the file path to write contents.
🌐
Programiz
programiz.com › java-programming › examples › create-and-write-to-file
Java Program to Create File and Write to the File
// importing the FileWriter class ... "System.out.println(\"This is file\");"+ "}"+ "}"; try { // Creates a Writer using FileWriter FileWriter output = new FileWriter("JavaFile.java"); // Writes the program to file output.write(program); System.out.println("Data is written to the ...
🌐
Baeldung
baeldung.com › home › java › java io › java – write to file
Java - Write to File | Baeldung
December 1, 2023 - Java 7 introduces a new way of working with the filesystem, along with a new utility class: Files. Using the Files class, we can create, move, copy, and delete files and directories.
🌐
How to do in Java
howtodoinjava.com › home › i/o › creating a new file in java
Creating a New File in Java
April 10, 2022 - Also, as from v1.3 this method creates parent directories if they do not exist. It throws an IOException if the last modified date of the file cannot be set. String TEXT_FILE = "C:/temp/io/textFile.txt"; org.apache.commons.io.FileUtils.touch(new File(TEXT_FILE)); Happy Learning !! ... A fun-loving family man, passionate about computers and problem-solving, with over 15 years of experience in Java and related technologies.
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-create-new-file
Java create new file | DigitalOcean
August 4, 2022 - If we run the program from command line, for the non-absolute path, File object tries to locate files from the current directory. While creating the file path, we should use System property file.separator to make our program platform independent. Let’s see different scenarios with a simple java program to create a new file in java.
🌐
Tutorialspoint
tutorialspoint.com › java › java_create_file.htm
Java - Creating Files
package com.tutorialspoint; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class FileTest { public static void main(String args[]) { try { File file = new File("d://test//testFile1.txt"); //Create the file if (file.createNewFile()) { System.out.println("File is created!"); } else { System.out.println("File already exists."); } // Write Content FileWriter writer = new FileWriter(file); writer.write("Test data"); writer.close(); // read content FileReader reader = new FileReader(file); int c; while ((c = reader.read()) != -1) { char ch = (char) c; System.out.print(ch); } } catch (IOException e) { System.out.print("Exception"); } } }
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-create-a-new-file
Java Program to Create a New File - GeeksforGeeks
December 4, 2025 - Explanation: The program reads the file name and path from the user using BufferedReader. Then it creates a FileOutputStream object with the full file path, if the file doesn’t exist, it’s created; if it already exists, it’s replaced.
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › io › file.html
Reading, Writing, and Creating Files (The Java™ Tutorials > Essential Java Classes > Basic I/O)
This option is equivalent to invoking the method with the CREATE and TRUNCATE_EXISTING options. The following example opens a log file. If the file does not exist, it is created. If the file exists, it is opened for appending. import static java.nio.file.StandardOpenOption.*; import java.nio.file.*; import java.io.*; public class LogFileTest { public static void main(String[] args) { // Convert the string to a // byte array.
🌐
TechVidvan
techvidvan.com › tutorials › create-open-delete-file-in-java
Java - Create file, Open File and Delete File - TechVidvan
June 17, 2020 - * ; public class FileOpen6 { public static List < String > readFileInList(String fileName) { List < String > lines = Collections.emptyList(); try { lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8); } catch(IOException e) { e.printStackTrace(); } return lines; } public static void main(String[] args) { System.out.println("File content:"); List l = readFileInList("D:\\TechVidvan.txt"); Iterator < String > itr = l.iterator(); //access the elements while (itr.hasNext()) //returns true if and only if scanner has another token System.out.println(itr.next()); //prints the conte
🌐
W3Schools
w3schools.com › java › java_files_write.asp
Java Write To Files
If you are just starting with Java, the easiest way to write text to a file is by using the FileWriter class. In the example below, we use FileWriter together with its write() method to create and write some text into a file.
🌐
Javatpoint
javatpoint.com › how-to-create-a-file-in-java
How to Create a File in Java - Javatpoint
How to Create a File in Java with oops, string, exceptions, multithreading, collections, jdbc, rmi, fundamentals, programs, swing, javafx, io streams, networking, sockets, classes, objects etc,
🌐
ZetCode
zetcode.com › java › createfile
Java create file - learn how to create a file in Java
The tutorials shows five ways to create a file in Java. The examples create empty files. The File's createNewFile method creates a new, empty file named by the pathname if a file with this name does not yet exist.
🌐
Intellipaat
intellipaat.com › home › blog › how to create and write to files in java?
How to Create and Write to Files in Java? - Intellipaat
February 2, 2026 - Overwrites the string at the beginning of the file with “Java Learner!” (the integer remains unchanged). Reads and prints the updated string to show the modification. If you need to write objects (including custom objects) to a file, ObjectOutputStream helps you to achieve this task. ... Code Copied! ... Explanation: The above code creates a Student object to a file (student.dat) using ObjectOutputStream (serialization) and reads the content of the file using ObjectInputStream (deserialization).