Write to file in Java

This tutorial would be focusing on different ways of write to file using Java. Stream is a general mechanism of I/O in java. Stream provides sequential access of data. An input stream can be used by an application to read data. An output stream to write data.

A file, network connection, arrays can act as stream.

Streams are categorized as:

  1. Byte Stream means Binary data
  2. Character Stream means Textual data

Whenever we have to make program of I/O then we use java.io package or java.nio package. In Java IO, there are some classes having words like Reader/Writer and Streams.  General rule is that, Reader and Writer are used for character based data (textual data) and streams are used for binary data. Here are some of the ways to write to a file.

1. Write to file in Java8

Java 8 provides a simple way to read and write strings to a text file. Here we read a file, add some more text and overwrite the file.

This contents of the source file named “source.txt”.

This is the program generated file named “dest.txt”

 

2.    BufferedWriter:

Buffer writer is inherited by the writer class. It is used to provide buffering from the Writer instances. It is used to write single arrays, characters, and strings.

Output:

Difference between FileWriter and BufferedWriter:

The FileWriter writes the characters one by one and the BufferedWriter first buffers it to the memory and writes it once.

In above program, if file is already existing, then whole content of a file will have removed and fresh content will be write on that file, means the existing data will be lost. So what if we want to keep old data and write some more data on same file? Here is the solution:

Let’s append the same file by adding a String to it.

Output:

Hello World New Content in the file

Note: FileWriter fileWriter = new FileWriter(file,true);

We pass an extra boolean parameter, it tells to the FileWriter for append mode. True means append mode is on.

3.    PrintWriter

Java PrintWriter class is the sub class of writer class It is used to print the representation of objects to the text-output stream.

This method is preferred for writing formatted text into a file.

Output:

This not only allows you to write the given string as it is but also let you format text into file for output. BufferedWriter and System.Out also support this writer.

Difference between FileWriter and PrintWriter:

  • The main difference is that PrintWriter offers some additional methods for formatting like println and printf.
  • PrintWriter automatically invokes flush after every byte of data is written. In case of FileWriter, caller must take care of invoking flush.

4.    FileOutputStream

If you have to write primitive values into a file, use FileOutputStream class. You can write byte-oriented similarly character-oriented data through FileOutputStream class. But, for character-oriented data, it is preferred to use File Writer than FileOutputStream.

Unlike above methods, FileOutputStream converts the input string data into its corresponding binary unit and process these binary bytes into a file. 

Output:

 5.    DataOutputStream:

Java DataOutputStream class allows an application to write primitive Java data types to the output stream in a machine-independent way.

This one is rather used for primitive data types. The following example shows how to write a string to a file using DataOutputStream.

Output:  The binary file will not be understandable.

DataOutputStream performs generally better because its much simpler. It can only write primitive types and Strings.

ObjectOutputStream can write any object type was well as primitives. It is less efficient but much easier to use if you want to send complex data.

6.    ObjectOutputStream:

ObjectOutputStream in Java can be used to convert an object to OutputStream. The process of converting object to stream is called serialization in java.

Once an object is converted to Output Stream, it can be saved to file or database, send over the network or used in socket connections. So, we can use FileOutputStream to write Object to file.

7.    RandomAccessFile

Java also allows you to access the contents of a file in random order i.e. data items can be read and written in any order. As the name suggest, it helps us to write in/Read from any position in a file given the position from beginning of a file (called offset).

Using RandomAccessFile, integer value is written to a file at an offset from the beginning of file.

8.  Write to file in Java7

 Introduction of new utility class File in Java 7 allow us to create, delete, move files and directories in addition to reading/ writing from/to file.

9.    Write data to temporary file

In Java you can write data into a temporary file as per the demand of program. Only the creation of temporary file is distinct and writing to it is same as we do for other files.

There are two methods in File class that we can use to create temp file in java:

  1. createTempFile(String prefix, String suffix, File directory)
  2. createTempFile(String prefix, String suffix)

If suffix is null, “.tmp” suffix is used. If directory is null, then temp file is created in operating system temp directory.

See below code is code, everything is same as above approaches except the way of creating file.

Conclusion:

So, these were the various ways to write to a file using Java. I hope you find them useful.  Suggestions are welcome in comments.

T Tak

Hey ! I'm Tak. I'm a software developer since 2008 and been programming since I was 17 years, started with pascal. I love programming, teaching and building stuff on web.

One thought to “Write to file in Java”

  1. I quite liked the way java 8 has provided the feature to write.
    But I think it is not helpful if you are dealing with multiple files as Files.lines method doesn’t close the file automatically. It needs to be in auto-closed mode.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.