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

🌐
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));
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › io › file.html
Reading, Writing, and Creating Files (The Java™ Tutorials > Essential Java Classes > Basic I/O)
File I/O Methods Arranged from Less Complex to More Complex · On the far left of the diagram are the utility methods readAllBytes, readAllLines, and the write methods, designed for simple, common cases. To the right of those are the methods used to iterate over a stream or lines of text, such as newBufferedReader, newBufferedWriter, then newInputStream and newOutputStream. These methods are interoperable with the java.io package.
🌐
Mkyong
mkyong.com › home › java › how to create a file in java
How to create a file in Java - Mkyong.com
July 14, 2020 - package com.mkyong.io.file; import ... java.nio.file.Paths; public class CreateFileJava8 { public static void main(String[] args) { String fileName = "/home/mkyong/newFile.txt"; Path path = Paths.get(fileName); // default, create, ...
🌐
W3Schools
w3schools.com › java › java_files_create.asp
Java Create Files
On Mac and Linux you can just write the path, like: /Users/name/filename.txt · File myObj = new File("C:\\Users\\MyName\\filename.txt"); ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript Tutorial How To Tutorial SQL Tutorial Python Tutorial W3.CSS Tutorial Bootstrap Tutorial PHP Tutorial Java Tutorial C++ Tutorial jQuery Tutorial
🌐
DataCamp
datacamp.com › doc › java › create-&-write-files
Java Create & Write Files
The FileWriter and BufferedWriter classes are commonly used for writing character data, while Files class methods can be used for both character and binary data. import java.io.FileWriter; import java.io.IOException; public class WriteFileExample { public static void main(String[] args) { try (FileWriter writer = new FileWriter("example.txt")) { writer.write("Hello, World!"); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } }
🌐
Baeldung
baeldung.com › home › java › java io › java – create a file
Java - Create a File | Baeldung
August 29, 2024 - 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.
🌐
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
🌐
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.
🌐
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 - Learn to create a new file using different techniques including NIO Files and Path, IO File, File OutputStream, and open-source libraries.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › nio › file › Files.html
Files (Java Platform SE 8 )
April 21, 2026 - Opens or creates a file, returning a seekable byte channel to access the file. 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 ...
🌐
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.
🌐
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.
🌐
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
🌐
ZetCode
zetcode.com › java › createfile
Java create file - learn how to create a file in Java
In Java create file tutorial, we show how to create a file in Java. We create files with built-in classes including File, FileOutputStream, and Files. We also use two third-party libraries: Apache Commons IO and Google Guava.
🌐
HappyCoders.eu
happycoders.eu › java › how-to-write-files-quickly-and-easily
How to Write Files Quickly and Easily (Java Files Tutorial)
November 29, 2024 - String fileName = ...; try (FileWriter writer = new FileWriter(fileName); BufferedWriter bufferedWriter = new BufferedWriter(writer)) { int c; while ((c = process()) != -1) { bufferedWriter.write(c); } }Code language: Java (java) BufferedWriter adds another 8 KB buffer for characters, which are then encoded in one go when the buffer is written (instead of character by character). This second buffer reduces the writing time for 100,000,000 characters to approximately 370 ms. In Java 7, the method Files.newBufferedWriter() was added to create a BufferedWriter:
🌐
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 - Learn to write text and binary data into files using Java Writer, FileChannel, ByteBuffer, Files.write() and writeString() methods in Java 8 and Java 11.
🌐
Tutorialspoint
tutorialspoint.com › java › java_create_file.htm
Java - Creating Files
String data = "Test data"; ... is the example to demonstrate File to create a file in given directory using Files.write() method − · package com.tutorialspoint; import java.io.IOException; import java.nio.chars...
🌐
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 ...