CodeGym /Java Blog /Java IO & NIO /Java – Write to File
Author
Milan Vucic
Programming Tutor at Codementor.io

Java – Write to File

Published in the Java IO & NIO group
One of the most common tasks in software development is the ability to read and write files. In Java, writing to a file is a straightforward process that can be done using built-in classes and methods. In this article, we will explore how to write to a file using Java and discuss the various classes and methods involved. Java provides built-in classes like FileWriter and PrintWriter to write into a file in Java.

Java Write to File Example

To begin with, let's look at a simple example of writing to a file in Java. Here's an example of how to write a string to a file in Java using the FileWriter class:

FileWriter class

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:

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


// Main method for the string to file in java starts from here,
public class WriteToFileExample {
    public static void main(String[] args) {
        // create a string to write text to file
        String data = "Hello, world!";

        try {
            // create a FileWriter object with the file name
            FileWriter writer = new FileWriter("output.txt");

            // write the string to the file
            writer.write(data);

            // close the writer
            writer.close();

            System.out.println("Successfully wrote text to file.");

        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}
In this example, we first create a String object named data that contains the text we want to write to a file. We then create a FileWriter object with the name of the file we want to write to, in this case, named output.txt. Next, we use the write() method of the FileWriter object to write the data string to the file. This method takes a String argument containing the data to write. Finally, we close the FileWriter object to release the file resources and print a success message to the console if the write operation is successful or an error message if an exception is caught. The FileWriter class is a simple way to write character data to a file in Java.

FileOutputStream Class

The FileOutputStream class is used to write data to a file as a stream of bytes. Here's an example:

import java.io.FileOutputStream;
import java.io.IOException;

public class WriteToFileExample {
    public static void main(String[] args) {
        String textToWrite = "Hello World!";

        try {
            FileOutputStream stream = new FileOutputStream("output.txt");
            byte[] bytesToWrite = textToWrite.getBytes();
            stream.write(bytesToWrite);
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
In this example, we create a FileOutputStream object named stream with the "output.txt" file name for writing to. We then convert the textToWrite string to a byte array using the getBytes() method and write the byte array to the stream object using the write() method. Finally, we close the stream object.

BufferedWriter Class

The BufferedWriter class is used to write text to a file with buffering capabilities. Here's an example:

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

public class WriteToFileExample {
    public static void main(String[] args) {
        String textToWrite = "Hello World!";

        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
            writer.write(textToWrite);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
In this example, we create a BufferedWriter object named writer with a FileWriter object that writes to the "output.txt" file. We then use the write() method of the writer object to write the textToWrite to the file. Finally, we close the writer object.

WriteString() method

The writeString() method is a convenient method introduced in Java 11 for writing a String to a file using the Files class. It allows you to write a String to a file in a single line of code. Here's an example:

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

public class WriteToFileExample {
    public static void main(String[] args) {
        // create a string to write to a file
        String data = "Hello, world!";

        // create a file object
        Path file = Paths.get("output.txt");

        try {
            // write the string to the file using writeString() method
            Files.writeString(file, data);

            System.out.println("Successfully wrote text to file.");

        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}
In this example, we first create a String object named data that contains the text we want to write to a file. We then create a Path object named file that represents the file we want to write to, in this case, named "output.txt". Next, we use the Files.writeString() method to write the data string to the file represented by the file object. This method takes two arguments: the Path object representing the file to write to, and the String object containing the data to write. Finally, we print a success message to the console if the write operation is successful or an error message if an exception is caught. The writeString() method is a convenient way to write a String to a file using Java 11 or later.

PrintWriter Class

The PrintWriter class automatically flushes the output buffer after each line is written, ensuring that the data is immediately written to the file. This makes it a convenient choice for writing large amounts of text data to a file. Here is an example:

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

public class WriteToFileExample {
    public static void main(String[] args) {
        String textToWrite = "Hello World!";

        try {
            PrintWriter writer = new PrintWriter(new FileWriter("output.txt"));
            writer.println(textToWrite);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
In this example, we create a PrintWriter object named writerwith a FileWrite object that writes to the "output.txt" file. We then use the println() method of the writer object to write the textToWrite to the file. Finally, we close the writer object.

DataOutputStream Class

The DataOutputStream class is used to write primitive Java data types to a file as a stream of bytes. Here's an example:

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteToFileExample {
    public static void main(String[] args) {
        String textToWrite = "Hello World!";
        int numberToWrite = 42;

        try {
            DataOutputStream stream = new DataOutputStream(new FileOutputStream("output.txt"));
            stream.writeUTF(textToWrite);
            stream.writeInt(numberToWrite);
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
In this example, we create a DataOutputStream object named stream, which writes to the "output.txt" file. We then use the writeUTF() method of the stream object to write the textToWrite string and the writeInt() method to write the numberToWrite integer to the file. Finally, we close the stream object. Java – Write to File - 1

FileChannel Class

The FileChannel class provides a way to write data to a file using memory-mapped I/O. Here's an example:

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class WriteToFileExample {
    public static void main(String[] args) {
        String textToWrite = "Hello World!";

        try {
            File file = new File("output.txt");
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
            FileChannel channel = randomAccessFile.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            buffer.put(textToWrite.getBytes());
            buffer.flip();
            channel.write(buffer);
            randomAccessFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
In this example, we first create a File object named file with the file name "output.txt" as a parameter. We then create a RandomAccessFile object named randomAccessFile with the file object and the "rw" mode as parameters. We then create a FileChannel object named channel, which is initialized using randomAccessFile object. We then create a ByteBuffer object named buffer with a capacity of 1024 bytes and put the textToWrite string as the parameter. We then flip the buffer object to prepare it for writing and write it to the channel object using the write() method. Finally, we close the randomAccessFile object.

Conclusion

In conclusion, writing to a file using Java is a common task in software development that can be done using several built-in classes and methods. In this article, we have discussed several examples of how to write into a file, including the use of FileOutputStream, BufferedWriter, FileWriter, PrintWriter, DataOutputStream, and FileChannel classes. It is important to note that when writing to a file, proper error handling and closing of the file after writing are crucial to ensure that the file is properly saved and the resources are properly released. With the examples provided in this article, beginners can now have a basic understanding of how to write to a file using Java and can start practicing and experimenting with different use cases.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION