How to Create a File and Write to It in Java: A Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Creating and Writing to a File in Java: Understanding It Once and For All

\n\n

The question "How do I create a file and write to it?" is one of the most popular on Stack Overflow. And it's no surprise: working with files is a fundamental skill that every Java developer learns. But the devil, as always, is in the details. Which class to choose? How not to lose data? How to handle exceptions? In this article, we won't just give a ready-made answer; we'll break down all the popular methods, their pros and cons, so you can confidently work with files in Java.

\n\n

We will look at creating a file and writing to it in Java, starting from the classic FileWriter and BufferedWriter to the modern Files.writeString(). Let's go!

\n\n

1. The Classic Way: FileWriter

\n\n

The simplest and most intuitive way to create a file and write text to it is to use java.io.FileWriter. It is specifically designed for writing character streams.

\n\n

How does it work?

\n

The FileWriter constructor takes a file name (or a File object). If the file does not exist, it will be created automatically. If the file exists, it will be overwritten (unless you specify the append flag).

\n\n
import java.io.FileWriter;\nimport java.io.IOException;\n\npublic class FileWriterExample {\n    public static void main(String[] args) {\n        try (FileWriter writer = new FileWriter("example.txt")) {\n            writer.write("Hello, world! This is the first line.\\n");\n            writer.write("And this is the second line.");\n            System.out.println("File successfully created and written!");\n        } catch (IOException e) {\n            System.err.println("Error working with file: " + e.getMessage());\n        }\n    }\n}\n
\n\n

Important: We use try-with-resources (Java 7+). This guarantees that the stream will be closed automatically, even if an exception occurs. Forgetting to close FileWriter is one of the most common mistakes beginners make.

\n\n

When to use FileWriter?

\n
    \n
  • For simple writing of small text files.
  • \n
  • When high performance is not required.
  • \n
  • For quick prototyping.
  • \n
\n\n

Cons

\n
    \n
  • Inefficient for writing large amounts of data (each write() call can lead to a system call).
  • \n
  • Does not support specifying encoding (uses the default encoding, which can cause problems on different platforms).
  • \n
\n\n

2. Performance and Reliability: BufferedWriter

\n\n

If you need to write a lot of data, use BufferedWriter. It wraps FileWriter and adds buffering. Data is first accumulated in a buffer and then written to the file in one large block. This significantly speeds up the operation.

\n\n
import java.io.BufferedWriter;\nimport java.io.FileWriter;\nimport java.io.IOException;\n\npublic class BufferedWriterExample {\n    public static void main(String[] args) {\n        String[] lines = {"Line 1", "Line 2", "Line 3"};\n\n        try (BufferedWriter writer = new BufferedWriter(new FileWriter("buffered_example.txt"))) {\n            for (String line : lines) {\n                writer.write(line);\n                writer.newLine(); // Adds a line separator, independent of the OS\n            }\n            System.out.println("File written via BufferedWriter.");\n        } catch (IOException e) {\n            System.err.println("Error: " + e.getMessage());\n        }\n    }\n}\n
\n\n

Note the newLine() method. Unlike \\n, it uses the system's line separator, making your code cross-platform.

\n\n

When to use BufferedWriter?

\n
    \n
  • For writing large text files.
  • \n
  • When performance is important

Blogs

Book Recommendations