JAVA IO - Write to a File using Java IO streams

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

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.

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 files. In Java, the java.io package provides a number of classes that will help users store the result in the file. This article will discuss a few methods for helping users store data in a file using the java.io package.

Methods to write a file in Java

1. Using FileWriter Class

Often, we need to write a small amount of content into a file. For that purpose, we use the 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 the IOException class.

Steps for writing into a file using FileWriter class:

1. First, create an instance of the FileWriter class and pass the file's relative path 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 the .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 the IOexception class in our code, exceptions need to be thrown out. We use this try-catch block to throw all the exceptions and test the code for errors.

Here's an example of writing into a file using the FileWriter class. In the following example, we will create a string and write that string into the "output.txt" file. For that, we will create an object of the FileWriter class and pass the relative path of the "output.txt" file in the object. Using the .write() method provided by FileWrite class, we will write the content of the 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 the same as FileWriter class because it is also used to write into a file for small text. 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. A sequence of characters (string) is encoded into bytes using a specified charset, and the open option specifies how the 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 to implement this method: IOException for throwing an exception, Files class for writing into the file, and Path class for getting 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 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: the path of the file and text.

Syntax

Files.writeString(p, text)

You can use the Files.readString(p) method to read the file's content from the Files class.

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. We will write the string into the file using the writeString() method. 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. The Final step is to close the file using the .close() method. This is necessary to prevent exceptions.

Syntax

f.close()

To throw exceptions, implement all the above steps in a try-catch block and the final statement.

Here's an example of writing into the file using the 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, we will convert the string into a byte array, and using the .write() function, we will write the byte array into the output stream that we created. Finally, we will close the file using the .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 efficiently write strings, single characters, 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 the BufferedWriter class and the 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 the BufferefWriter class; get an output stream using the 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 the .write(text) function. However, we can write integers, characters, and arrays 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 the BufferedWriter class. In the following example, first, we will create a string that needs to be written into the file. As the BufferedWriter class needs an output stream as a parameter, we pass the output stream of the FileWriter class by creating its object. Later, we write into the BufferedWriter object 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 and threads in parallel). By invoking one of the open methods, a 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. 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 the fileChannel class needs a channel of the output stream, we need to convert an output stream into a channel to implement the .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. Use the .rewind() method to set the buffer's position to zero. As the buffer's position may have an arbitrary value at the start, we need to initialize it 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. The fileChannel class requires an output stream channel to write into the file, so we get the output stream's channel by using the .getChannel() method provided by the FileOutputStream class. To write any text into the channel, we need to convert the text into a buffer of bytes, so we will create a ByteBuffer of size 50 bytes(allocate size according to your need). Put all the bytes into the channel using the .put() method. Initialize the position of the buffer to zero by using .rewind() method. Finally, we will write into the channel using the .write() method and close the channel using the .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) and 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 file's contents, 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 that allows us to write integers, strings, parts of strings, bytes, and others into the file. The writeString method of the FileWriter class is used to write only specified strings into the file. It takes a string as an argument and does not return any value.

  • FileOutputStream is a byte stream that writes the data into the file in binary format, which is exactly 8-bit.
  • BufferedWriter writes the text to the character-output stream. It provides efficient writing of arrays, strings, and single characters. FileChannel helps write 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.