Skip to content

Writing a file in Java

Writing a file in Java involves a few key steps: creating a file object, opening a stream to the file, writing data to the stream, and finally, closing the stream to ensure everything is safely saved.

Let's walk through these steps together with a simple example:

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

public class FileWriterExample {
    public static void main(String[] args) {
        // Define the file path
        String filePath = "my_story.txt";

        try {
            // Create a FileWriter object
            FileWriter writer = new FileWriter(filePath);

            // Write data to the file
            writer.write("Once upon a time, in a land far, far away...\n");
            writer.write("There lived a brave knight named Sir Java.\n");

            // Close the FileWriter stream
            writer.close();

            System.out.println("File '" + filePath + "' has been written successfully!");
        } catch (IOException e) {
            System.out.println("An error occurred while writing the file: " + e.getMessage());
        }
    }
}

In our example, we create a file named "my_story.txt" and write a couple of lines to it. Let's break down what's happening:

  • We define the file path where we want to save our story.
  • Inside a try block, we create a FileWriter object, passing the file path as an argument.
  • We use the write() method of the FileWriter to write our story lines to the file.
  • Finally, we close the FileWriter stream to ensure everything is safely written.

Using java.nio

NIO provides a more efficient and flexible way to work with files compared to traditional I/O. It offers features like buffers, channels, and non-blocking I/O, empowering you to write files with speed and elegance.

Now, let's unleash the power of NIO with a captivating example:

java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class NIOFileWriterExample {
    public static void main(String[] args) {
        // Define the file path
        Path filePath = Paths.get("my_story.txt");

        try {
            // Write data to the file using NIO
            Files.write(filePath, "Once upon a time, in a land far, far away...\n".getBytes());
            Files.write(filePath, "There lived a brave knight named Sir Java.\n".getBytes(), StandardOpenOption.APPEND);

            System.out.println("File '" + filePath + "' has been written successfully!");
        } catch (IOException e) {
            System.out.println("An error occurred while writing the file: " + e.getMessage());
        }
    }
}

In our example, we use NIO's Files.write() method to write data to a file named "my_story.txt". Let's break down what's happening:

  • We define a Path object representing the file path.
  • Inside a try block, we use Files.write() to write our story lines to the file.
  • We use getBytes() to convert our string data into bytes, which is the format NIO expects.
  • We also use StandardOpenOption.APPEND to append data to the file, ensuring our story lines are added to the existing content.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.