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
🌐
Medium
medium.com › @AlexanderObregon › javas-files-write-method-explained-288e75dfc721
Java’s Files.write() Method Explained | Medium
March 20, 2025 - In this example, Files.write() writes a list of strings to a file called example.txt using the UTF-8 charset. If the file doesn't exist, it will be created automatically.
🌐
W3Schools
w3schools.com › python › python_file_write.asp
Python File Write
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Training ... with open("demofile.txt", "a") as f: f.write("Now the file has more content!") #open and read the file after the appending: with open("demofile.txt") as f: print(f.read()) Run Example »
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).

🌐
Java Guides
javaguides.net › 2019 › 07 › java-write-file-with-fileswrite-api.html
Java Files write() Method Example
June 21, 2024 - In this example, a file named example.txt is created or appended to with a list of strings. The code handles exceptions to ensure that informative messages are displayed if an error occurs. The Files.write() method in Java provides a simple and efficient way to write data to a file.
🌐
CodeSignal
codesignal.com › learn › courses › fundamentals-of-text-data-manipulation-in-r-1 › lessons › writing-to-files-in-r
Writing to Files in R | CodeSignal Learn
This example converts the number 42 to a string using as.character() before writing to the file. When executed, output.txt will contain: With this approach, you can handle and store numerical data in text files easily. ... In this lesson, we've mastered how to write and append text to files using R's writeLines() and write() functions and validated these processes using readLines().
🌐
GeeksforGeeks
geeksforgeeks.org › python › writing-to-file-in-python
Writing to file in Python - GeeksforGeeks
Opening a file in write mode ("w") clears any existing content before writing new data. This is useful when you want to start fresh and replace old information with new output. Example: This code writes two lines to file.txt, overwriting any ...
Published   April 4, 2026
🌐
W3Schools
w3schools.com › java › java_files_create.asp
Java Create Files
To create a file in a specific directory (requires permission), specify the path of the file and use double backslashes to escape the "\" character (for Windows). On Mac and Linux you can just write the path, like: /Users/name/filename.txt · File myObj = new File("C:\\Users\\MyName\\filename.txt"); Run Example » ·
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-filewriter-example
Java FileWriter Example | DigitalOcean
August 4, 2022 - Its write() methods allow you to write character(s) or strings to a file.
Find elsewhere
🌐
DataCamp
datacamp.com › doc › java › create-&-write-files
Java Create & Write Files
The write() method is convenient for writing small to medium-sized files. Exception Handling: Always handle IOException when dealing with file operations to manage potential errors gracefully. Resource Management: Use try-with-resources to ensure that file resources are closed properly, preventing resource leaks. Character Encoding: Specify a character encoding when writing files to avoid platform-dependent issues. new FileWriter("example.txt", StandardCharsets.UTF_8)
🌐
Microsoft Learn
learn.microsoft.com › en-us › windows › win32 › api › fileapi › nf-fileapi-writefile
WriteFile function (fileapi.h) - Win32 apps | Microsoft Learn
March 3, 2025 - The following C++ example shows how to align sectors for unbuffered file writes. The Size variable is the size of the original data block you are interested in writing to the file.
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-write-to-file
Java Write to File - 4 Ways to Write File in Java | DigitalOcean
August 3, 2022 - Files: Java 7 introduced Files utility class and we can write a file using its write function. Internally it’s using OutputStream to write byte array into file. Here is the example showing how we can write a file in java using FileWriter, BufferedWriter, FileOutputStream, and Files in java.
🌐
W3Schools
w3schools.com › c › c_files_write.php
C Write To Files
To insert content to it, you can use the fprintf() function and add the pointer variable (fptr in our example) and some text: FILE *fptr; // Open a file in writing mode fptr = fopen("filename.txt", "w"); // Write some text to the file fprintf(fptr, ...
🌐
DataCamp
datacamp.com › tutorial › python-write-to-file
Python Write to File: Working With Text, CSV, and JSON Files | DataCamp
January 21, 2026 - Run this script, and Python creates a file called example.txt in the same directory as your code. ... This works, but it’s not how you should write files long-term.
🌐
LearnPython.com
learnpython.com › blog › write-to-file-python
How to Write to File in Python | LearnPython.com
Discover how to write to a file in Python using the write() and writelines() methods and the pathlib and csv modules.
🌐
Baeldung
baeldung.com › home › java › java io › java – write to file
Java - Write to File | Baeldung
December 1, 2023 - If we try to write to a file that doesn’t exist, the file will be created first and no exception will be thrown. It is very important to close the stream after using it, as it is not closed implicitly, to release any resources associated with it. In output stream, the close() method calls flush() before releasing the resources, which forces any buffered bytes to be written to the stream. 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.
🌐
Go by Example
gobyexample.com › writing-files
Go by Example: Writing Files
Writing files in Go follows similar patterns to the ones we saw earlier for reading · To start, here’s how to dump a string (or just bytes) into a file
🌐
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
123456789101112131415161718192... Create a FileWriter wrapped with a BufferedWriter BufferedWriter writer = new BufferedWriter(new FileWriter(filename)); // Write lines of text to the file writer.write("Hello, this is the ...
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › standard › io › how-to-write-text-to-a-file
How to: Write text to a file - .NET | Microsoft Learn
October 21, 2025 - The following example shows how to use the StreamWriter class to synchronously write text to a new file one line at a time.
🌐
W3Schools
w3schools.com › python › ref_file_write.asp
Python File write() Method
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Training ... f = open("demofile2.txt", "a") f.write("See you soon!") f.close() #open and read the file after the appending: f = open("demofile2.txt", "r") print(f.read()) Run Example »
🌐
CodeGym
codegym.cc › java blog › java io & nio › java – write to file
Java – Write to File
December 26, 2024 - The FileWriter class is another way to write to a file in Java. It is a character stream class that allows you to write character data to a file. Here's an example that demonstrates how to use the FileWriter class to write a String to a file: