How to Write Array to File in Java

In this post, we will see how to write array to file in java.

Ways to Write Array to File in Java

There are different ways to write array to file in java. Let’s go through them.

Using BufferWriter

Here are steps to write array to file in java:

  • Create new FileWriter and wrap it inside BufferedWriter.
  • Iterate over the array and use write() method to write content of the array
  • Once done close and flush BufferedWriter obj.

Output:
Write array to file in java

Using ObjectOutputStream

You can use ObjectOutputStream to write object to underlying Stream. This is also know as Serialization in java.
Here are the steps:

  • Create new FileOutputStream and write it in ObjectOutputStream.
  • Use writeObject() method to write object to the file.

Please note that content of the tempObj.txt file won’t be in readable format.

To read the array back, you need to use ObjectInputStream.

Here is an example to read file back into the array.

Output

That’s all about how to write array to File in Java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *