๐Ÿ“‚ Java File Handling
Estimated reading: 4 minutes 441 views

Java Create and Write Files โ€“ FileWriter, BufferedWriter, Files API


Introduction โ€“ Why File Creation & Writing Matters

In any modern application, saving data to a file is fundamental โ€” whether you’re generating logs, saving user input, or exporting reports. Java provides a rich set of APIs to create and write files easily using both the traditional java.io package and the modern java.nio.file API.

By the end of this guide, you’ll know:

  • How to create new files in Java
  • How to write data to files
  • The difference between FileWriter, BufferedWriter, and Files.write()
  • Best practices for safe and efficient file operations

Java Packages Used

PackagePurpose
java.ioClassic file handling tools
java.nio.fileModern and efficient file APIs

Creating a File in Java

Using File Class (java.io)

import java.io.File;
import java.io.IOException;

public class CreateFileExample {
    public static void main(String[] args) {
        try {
            File file = new File("example.txt");
            if (file.createNewFile()) {
                System.out.println("File created: " + file.getName());
            } else {
                System.out.println("File already exists.");
            }
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

Explanation:

  • createNewFile() creates the file if it doesnโ€™t already exist.
  • Returns true if created, false if it already exists.
  • Requires handling IOException.

Writing to a File

Using FileWriter (Basic)

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("Java file writing example.");
            writer.close();
            System.out.println("Successfully wrote to the file.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  • FileWriter writes characters to the file.
  • close() must be called to release resources and flush data.

Warning: This method overwrites existing file content by default.


Appending to a File with FileWriter

FileWriter writer = new FileWriter("example.txt", true);
writer.write("\nAppending new line to file.");
writer.close();

Explanation:

  • The second argument true enables append mode.

Using BufferedWriter for Efficiency

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriteExample {
    public static void main(String[] args) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt", true))) {
            writer.write("BufferedWriter makes writing efficient.\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  • BufferedWriter adds a buffer layer for faster writes.
  • Uses try-with-resources to auto-close the writer.

Writing Files with Java NIO (Files.write())

Writing a Single Line

import java.nio.file.*;
import java.io.IOException;

public class NIOWriteExample {
    public static void main(String[] args) throws IOException {
        String content = "This is written using java.nio.file!";
        Files.write(Paths.get("nio-example.txt"), content.getBytes());
    }
}

Explanation:

  • Files.write() writes a byte array to a file.
  • Automatically creates the file if it doesnโ€™t exist.

Writing Multiple Lines

import java.util.List;

List<String> lines = List.of("Line 1", "Line 2", "Line 3");
Files.write(Paths.get("multilines.txt"), lines, StandardOpenOption.CREATE);

Explanation:

  • Writes each string in the list as a new line in the file.

Writing with Options

OptionDescription
StandardOpenOption.CREATECreates the file if it doesn’t exist
StandardOpenOption.APPENDAppends data to file
StandardOpenOption.TRUNCATE_EXISTINGTruncates existing content

Example with append:

Files.write(Paths.get("file.txt"), List.of("Another Line"), StandardOpenOption.APPEND);

Best Practices for File Creation & Writing

  • Always use try-with-resources for automatic stream closing
  • Use BufferedWriter for better performance on large writes
  • Avoid overwriting important data โ€” use APPEND mode if needed
  • Prefer java.nio.file for modern Java applications
  • Handle exceptions properly to avoid data corruption or crashes

Summary โ€“ Creating and Writing Files in Java

Java offers multiple flexible APIs for creating and writing to files โ€” from simple text files to complex I/O operations.

Key Takeaways:

  • Use File to check and create files
  • Use FileWriter or BufferedWriter for classic I/O
  • Use Files.write() for modern, efficient file writing
  • Always manage exceptions and close streams safely

Whether you’re generating logs or saving user input, Java equips you with powerful tools for file operations.


FAQs โ€“ Java Create/Write Files

How do I create a new file in Java?

Use File.createNewFile() or Files.write() with StandardOpenOption.CREATE.

What’s the difference between FileWriter and BufferedWriter?

BufferedWriter wraps FileWriter and improves performance with buffering.

How to append content to a file?

Pass true to FileWriter, or use Files.write() with StandardOpenOption.APPEND.

Can Files.write() create the file automatically?

Yes, it creates the file if it doesnโ€™t exist.

Is java.nio.file better than java.io?

Yes. Itโ€™s modern, concise, and supports better exception handling and performance.


Share Now :
Share

Java Create/Write Files

Or Copy Link

CONTENTS
Scroll to Top