In this article, we will be learning about the different ways in which you can write to a text file in Java.
Using FileWriter
Java has an in-built class called java.io.FileWriter. It represents a character stream, that is it can be used to write characters to a file. It has a method called write which accepts a String parameter and writes it to the file.
Sample Code
FileWriter fileWriter = new FileWriter("C:/output.txt"); String str = "Hello World using FileWriter"; fileWriter.write(str); fileWriter.close();
- Line 1 creates a FileWriter object called fileWriter corresponding to the file that needs to be written to.
- Line 2 declares and initializes a String called str.
- Line 3 invokes the write method with str. This writes str to the file c:/output.txt
- There are other overloaded versions of the write method that can be used to write a part of a String, a character array, a part of a character array, a single character, etc.
Using BufferedWriter
The FileWriter class seen above has one limitation. It performs an IO operation each time the write method is invoked. So, it is not very performance efficient. Java has another class called java.io.BufferedWriter which overcomes this limitation. BufferedWriter has an internal buffer which is a character array. When the write method is invoked on a BufferedWriter object, it writes data into this internal buffer and not directly to the file. The file is written to only when the internal buffer is full or when the BufferedWriter is closed. Thus, this reduces the number of IO operations and improves the performance. The BufferedWriter class cannot be used by itself, it is used in conjunction with a FileWriter.
Sample Code
FileWriter fileWriter = new FileWriter("C:/output.txt"); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); String str = "Hello World using BufferedWriter"; bufferedWriter.write(str); bufferedWriter.close(); fileWriter.close();
- Line 1 creates a FileWriter object called fileWriter corresponding to the output file
- Line 2 creates a BufferedWriter called bufferedWriter corresponding to fileWriter. By default, this creates a BufferedWriter with an internal buffer that is capable of storing 8192 characters. There is also an overloaded BufferedWriter constructor which accepts an int value corresponding to the size of the internal buffer and creates a BufferedWriter object accordingly.
- Line 4 invokes the write method on bufferedWriter. This writes to the internal buffer and not to the file
- Line 5 invokes the close method on bufferedWriter. This flushes the bufferedWriter, that is its contents are written to the file.
The code above writes a single String to the file. Hence, in this case, the BufferedWriter is not much more efficient than a FileWriter since both perform one write operation to the underlying file. The BufferedWriter is more efficient than a FileWriter when multiple write operations are performed.
Sample Code
FileWriter fileWriter = new FileWriter("C:/output.txt"); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); List<String> content = new ArrayList<>(); for(int i=0;i < 100;i++) { content.add("Hello. I am line "+i+". "); } for(String str:content) { bufferedWriter.write(str); } bufferedWriter.close(); fileWriter.close();
- Line 1 creates a FileWriter object called fileWriter corresponding to the output file
- Line 2 creates a BufferedWriter called bufferedWriter corresponding to fileWriter.
- Line 3 declares a String array called content
- Lines 4-6 add some strings to content via a for loop.
- Lines 7-9 specify another for loop. It iterates over the content array and invokes the bufferedWriter.write method on each String in the content array.
- Each call to bufferedWriter.write writes to the internal buffer and not to the actual file. If a FileWriter had been used instead of BufferedWriter, each call to the write method would have written to the file system. Thus, this would have resulted in an IO operation for each iteration of the loop. The BufferedWriter avoids this by only performing an IO operation when the internal buffer is full or when the BufferedWriter is closed.
Using PrintWriter
Java has an in-built class called java.io.PrintWriter. It can be used to write formatted representations of objects to an output stream. It has a method called write which accepts as parameter a String and writes it to the file system.
Sample Code
PrintWriter printWriter = new PrintWriter("C:/output.txt"); String str = "Hello World using PrintWriter"; printWriter.write(str); printWriter.close();
- Line 1 creates a PrintWriter object called printWriter corresponding to the output file.
- Line 3 invokes the write method with the String str.
The write method demonstrated above simply writes the data to the output file. The PrintWriter class also another method called print which also formats the output.
Sample Code
PrintWriter printWriter = new PrintWriter("C:/output.txt"); String str = "Hello World using PrintWriter.print"; printWriter.print(str); printWriter.close();
- Line 1 creates a PrintWriter object called printWriter corresponding to the output file.
- Line 3 invokes the print method with the String str.
- There are other overloaded versions of the print method that can be used to write other types of data like int, float, etc.
Using Files
Java has an in-built class called java.nio.Files. It has a lot of utility methods that can be used to perform operations on files.
It has a method called writeString. It can be used to write a String to a file. It accepts as parameter a Path object, the String to be written and an OpenOption instance. Path is a class in the java.nio package which represents the path of a file on the file system. OpenOption is an interface in the java.nio package which specifies how to open the file.
Sample Code
Path path = Paths.get("C:/output.txt"); String str = "Hello World using Files"; Files.writeString(path, str,StandardOpenOption.CREATE);
- Line 1 creates a Path object called path corresponding to the output file.
- Line 3 invokes the Files.writeString method using path, the String str and StandardOpenOption.CREATE. StandardOpenOption is an enum that implements the OpenOption interface. It has enum constants that specify how the file should be opened. CREATE specifies that a new file should be created if it does not exist.
The Files class also has a method called write. It can be used to write a byte array to a file on the file system. It accepts as parameter a Path object and a byte array and writes the specified byte array to the file.
Sample Code
Path path = Paths.get("C:/output.txt"); String str = "Hello World using Files"; Files.write(path, str.getBytes());
- Line 1 creates a Path object called path corresponding to the output file.
- Line 3 invokes the Files.write method using path and a byte array corresponding to the input String str.
Conclusion
So, in this article, we saw the various ways in which you can write to a file in Java. We first saw how to write a file using a FileWriter, BufferedWriter and PrintWriter. We then took a look at the Files class and the methods in the Files class like writeString and write which can also be used to write to a file.