JAVA IO - Write to a File using Java IO streams
Learn via video course
Overview
In Java, many techniques can be used to write into a file. java.io.File, java.io.FileWriter, java.io.BufferedWriter, java.io.FileOutputStream, etc., are some of the classes in Java that help to write in a file. By creating an object of the above-mentioned classes we can access the methods of that class that are used to write into a file. All the above-mentioned classes are included inside a single package called java.io. The java.io package provides various input and output streams that enable us to read data from the file, and write data into the file.
Scope of the article
- In the article, we will discuss some techniques to write into the file in Java and why there is need of writing into the file.
- We will see the implementation of many classes along with the explanation that will help in writing into the file.
Introduction
In real-world applications, people run many programs and get their outputs. Sometimes storing the result of the executed program is necessary as the output may be needed for later use. So, the output displayed on the screen must be stored in the files. In Java, the java.io package provides a number of classes that will help users to store the result into the file. In this article, we will discuss a few methods that will help users store data into the file using the java.io package.
Methods to write a file in Java
1. Using FileWriter Class
Often we need to write a small content into a file for that purpose, we use FileWriter class. To implement this class, we need to import the FileWriter class. While writing the data into the file there may be several exceptions, to throw the exceptions we will import IOException class.
Steps for writing into a file using FileWriter class:
1. First, create an instance of FileWriter class, and pass the relative path of the file into it.
Syntax
FileWriter f = new FileWriter(“filename.txt”)
2. Use the newly created instance and pass the string parameter by using .write() method. (We can pass int, char, char array and string to this method)
Syntax
f.write(string)
3. Lastly, close the file using .close() method, by closing this file exceptions will not be generated.
Syntax
f.close()
Perform all the operations using a try-catch block to print all the exceptions. As we are using IOexception class in our code, exceptions need to be thrown out. For throwing all the exceptions and testing the code for errors, we use this try-catch block.
Here's an example of writing into a file using the FileWriter class. In the following example we will create a string and will write that string into the "output.txt" file. For that we will create and object of FileWriter class and pass the relative path of the "output.txt" file in the object. Using .write() method provided by FileWrite class we will write the content of string into the file. Finally, we close the file using .close() method.
Code
Output
Explanation
The “output.txt” file will contain the following text:
Hello Welcome to Scaler!
Also, the terminal will display the following message:
Content is successfully added into the output.txt file.
2. Using writeString() method
This method is also the same as FileWriter class because it is also used to write into a file for small texts. But the writeString() method takes four parameters. Among the four parameters first two are mandatory. The first two mandatory parameters are relative file path and the text that we need to write into the file. The other two parameters are charset and open option. As sequence of charaters(string) is encoded into bytes using specified charset, and the open option specifies how file is created or opened. We have CREATE, OPEN and TRUNCATE_EXISTING options available. In other words, it opens the file for writing, creating the file if the file doesn't exist, or initially truncating(making short) an existing regular-file to a size of 0. We need to import three classes in order to implement this method namely, IOException for throwing an exception, Files class to write into the file, and the Path class to get the path of the file(the file in which the user is going to write).
Steps for writing into a file using writeString class:
1. Get the relative path of the file in which the user wants to write using the Path class.
Syntax
Path p = Path.of(“output.txt”)
2. Use the writeString() method of the Files class and pass two parameters first is a path of the file, and the second is text.
Syntax
Files.writeString(p, text)
You can use the Files.readString(p) method from the Files class to read the content of the file.
Here's an example of writing into the file using FileOutputStream class. In the following example, first, we will create a string that needs to be written into the file. Furthermore, we will get the path of the file in which string is to be written using the Path class. By using the writeString() method, we will write the string into the file. To check whether the string is written into the file, we will use the readString() method to read the file's contents.
Code
Output
Explanation
The “output.txt” file will contain the following text:
Hello Welcome to Scaler!
Also, the terminal will display the contents of the file:
Hello Welcome to Scaler!
3. Using FileOutputStream class
FileOutputStream class is used to write raw data stream into the file. Normally, we can write text into the file, but we can also write binary data into the file by using the .write() method provided by this class. We can only write byte-oriented and character-oriented data into the file by using FileOutputStream class. To implement this class, we need to import FileOutputStream class.
Steps for writing into a file using FileOutputStream class:
1. First, create an object of FileOutputStream class. It takes an argument, i.e., a relative path of the file.
Syntax
FileOutputStream f = new FileOutputStream(“output.txt”)
2. Convert the string(that is to be written into the file) into bytes and store it in the byte array.
Syntax
byte[] bytes_array = string.getBytes()
3. Now, use the .write() method of FileOutputStream and pass the byte array into it.
Syntax
f.write(bytes_array)
4. Final step is to close the file using the .close() method. It is necessary to close the file in order to prevent exceptions.
Syntax
f.close()
Implement all the above steps in a try-catch block, and final statement in order to throw exceptions.
Here's an example of writing into the file using FileOutputStream class. In the following example, first, we will create a string that needs to be written into the file. Then we will create an object of FileOutputStream. Later on, we will convert the string into a byte array, and by using the .write() function, we will write the byte array into the output stream that we created. Finally we close the file using .close() method.
Code
Output
Explanation
The “output.txt” file will contain the following text:
Hello Join Scaler Today!
Also, the terminal will display the contents of the file:
Content is successfully added into the output.txt file.
4. Using BufferedWriter class
The .write() method of BufferedWriter class in Java is used to write the text in a character-output stream. Buffering characters provide the efficient writing of strings, single character, and arrays. In the BufferedWriter class, users can also define their own buffer size, although it has a default buffer size that is large enough for many purposes. In order to implement this class, we need to import BufferedWriter class and FileWriter class. BufferedWriter class needs a character output stream as a parameter, so in order to create a character output stream, we require the FileWriter class.
Steps for writing into a file using BufferedWriter class:
1. First, create an object of BufferefWriter class; get an output stream using FileWriter class.
Syntax
BufferedWriter f = new BufferedWriter(new FileWriter(“output.txt”))
2. Now write the content(string) into the buffer that we have created using .write(text) function. However we can write integer, character and array of characters into the file instead of using the string.
Syntax
f.write(content)
3. Lastly, close the BufferedWriter object using .close() function.
Syntax
f.close()
Here's an example of writing into the file using BufferedWriter class. In the following example, first, we will create a string that needs to be written into the file. As BufferedWriter class needs an output stream as a parameter, we pass the output stream of FileWriter class by creating its object. Later we write into the BufferedWriter object by using the .write() method. Finally, we close the file using the .close() method.
Code
Output
Explanation
The “output.txt” file will contain the following text:
Hello welcome to Scaler!
Also, the terminal will display the contents of the file:
Content is successfully added into the output.txt file.
5. Using FileChannel class
FileChannel class in Java is used for reading, writing, mapping, and manipulating a file. In this section, we will discuss the .write() method that is used to write into the file. An “open for writing” instance is required to implement this class. FileChannel class is safe for use by multiple concurrent threads (concurrency is the ability to run several programs, threads in parallel). By invoking one of the open methods, file channel is created. We can also obtain a file channel by invoking the getChannel() method of an existing FileOutputStream object, which returns a file channel that is connected to the same file. I will discuss one of the methods to write into a file using FileChannel class. For that, we need to import FileOutputStream class, ByteBuffer class, and FileChannel class.
Steps for writing into a file using FileChannel class:
1. First, we will create an object of FileOutputStream. We pass the relative path of the file as an argument.
Syntax
FileOutputStream f = new FileOutputStream("output.txt")
2. Now, we will obtain a channel of an opened output stream using the getChannel() method. As fileChannel class needs channel of output stream so we need to convert a output stream into a channel to implement .write() method.
Syntax
FileChannel f_channel = f.getChannel()
3. Create an object of ByteBuffer and allocate some space to store the text that needs to be written into the file. ByteBuffer provides a buffer that helps in transferring bytes from source to destination.
Syntax
ByteBuffer bb = ByteBuffer.allocateDirect(space)
4. Put all the bytes of data into the buffer.
Syntax
bb.put((byte) content.charAt(i))
5. Set the position of the buffer to zero by using the .rewind() method. As the buffer's position may have an arbitrary value at the start, we need to initialize the position of the buffer to zero.
Syntax
bb.rewind()
6. Write the bytes into the channel using the .write() method provided by FileChannel class.
Syntax
f_channel.write(bb)
7. Lastly, close the file using the .close() method.
Syntax
f_channel.close()
Here's an example of writing into the file using FileChannel class. In the following example, first, we will create a string that needs to be written into the file. Then we will create an output stream using a FileOutputStream class. FileChannel class requires a channel of output stream to write into the file so we get the channel of the output stream by using .getChannel() method provided by FileOutputStream class. To write any text into the channel we need to convert the text into buffer of bytes so we will create a ByteBuffer of size 50 bytes(allocate size according to your need). Now put all the bytes into the channel using .put() method. Initialize the position of the buffer to zero by using .rewind() method. Finally we will write into the channel using .write() method and close the channel using .close() method.
Code
Output
Explanation
The “output.txt” file will contain the following text:
Hello guys visit Scaler for more awesome blogs!
Also, the terminal will display the contents of the file:
Content is successfully added into the output.txt file.
6. Using DataOutputStream class
To write primitive data types into the output stream in a portable way, we use DataOutputStream class because it formats the data in a platform-independent way. The data output stream is typically used by Java applications to write data that a data input stream can later read. DataOutputStream has many methods, such as writeInt(used to write an integer to the output stream), writeChar(used to write a character to an output stream). Similarly, there are other methods like writeByte, writeBytes, writeLong, writeShort, writeBoolean. To implement this class we need to import DataOutputStream class and FileOutputStream class.
Steps for writing into a file using DataOutputStream class:
1. First, create an object of FileOutputStream.
Syntax
FileOutputStream fo = new FileOutputStream("output.txt")
2. Now, create an object of DataOutputStream by passing an object of FileOutputStream as a parameter. Here, FileInputStream provides an output stream that is needed for the object of DataObjectStream.
Syntax
DataOutputStream dfo = new DataOutputStream(fo)
3. Write into the stream by using any of the write method i.e., .writeInt(), .writeDouble(), .writeChar(), etc.,
4. Flush the DataOutputStream using the .flush() function. Flush forces the bytes to be written to the underlying stream.
Syntax
dfo.flush()
5. Close the DataOutputStream using .close() function.
Syntax
dfo.close()
To read the contents of the file use DataInputStream as shown in the following program.
Here's an example of writing into the file using DataOutputStream class. In the following example, first, we will create a string that needs to be written into the file. Furthermore, we will create an output stream using the FileOutputStream class and provide it to the object of DataOutputStream class. Now we will perform several methods like .writeInt(), .writeDouble(), etc. Flush the current stream using the .flush() method. Finally, close the DataOutputStream by using .close() method.
Code
Output
Explanation
The output file will contain the following text.
0000 0037 4063 0828 f5c2 8f5c 0047
The terminal will have the following output:
Content is successfully added into the output.txt file.
Integer value of the file: 55
Double value of the file: 152.255
Char value of the file: G
Conclusion
- FileWriter is the simplest way to write into a file because it provides most of the features like an overloaded write method where we can write integer, string, part of the string, and bytes into the file and others.
- writeString method of FileWriter class is used to write only specified strings into the file. It takes a string as an argument. The method does not return any value.
- FileOutputStream is a byte stream that writes the data into the file in binary format, exactly 8-bit.
- BufferedWriter writes the text to the character-output stream. It provides efficient writing of arrays, strings, and single characters.
- FileChannel helps in writing at a specific position in a file. The transfer of file data from one channel to another is faster.
- DataOutputStream enables us to efficiently write byte, char, int, boolean, etc., into the output stream.