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

Gareth D.

The ProblemJump To Solution

How do I create a file and write to it in Java?

The Solution

There are many different ways to write data to a file in Java, but the easiest way is to use a BufferedWriter along with a FileWriter, as follows.

Click to Copy
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"); } } }

This will write “Java files are easy” to a file called newfile.txt in the same directory as your Main.java file. If the file already exists, it will be overwritten.

If you want to append data to an existing file, you can pass true as a second argument to FileWriter. This enables append mode, so the file will not be overwritten.

Click to Copy
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.

Further reading

  • Sentry BlogException Handling in Java (with Real Examples)
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty Treats for Web Developers brought to you by Sentry. Web development tips and tricks hosted by Wes Bos and Scott Tolinski

    Listen to Syntax

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.