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 insideBufferedWriter
. - Iterate over the array and use
write()
method to write content of the array - Once done close and flush
BufferedWriter
obj.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package org.arpit.java2blog; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class WriteArrayToFileMain { public static void main(String[] args) throws IOException { int[] intArr = {1,2,3,4,5}; String fileName= "C:\\Users\\Arpit\\Desktop\\TxtFiles\\temp.txt"; write(fileName,intArr); } public static void write (String filename, int[]arr) throws IOException { BufferedWriter ow = null; ow = new BufferedWriter(new FileWriter(filename)); for (int i = 0; i < arr.length; i++) { ow.write(arr[i]+""); ow.newLine(); } ow.flush(); ow.close(); } } |
Output:
Further reading:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package org.arpit.java2blog; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class WriteArrayToFileObjectOutputStreamMain { public static void main(String[] args) throws IOException { int[] intArr = {1,2,3,4,5}; String fileName= "C:\\Users\\Arpit\\Desktop\\TxtFiles\\tempObj.txt"; ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(fileName)); outputStream.writeObject(intArr); } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package org.arpit.java2blog; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.util.Arrays; public class ReadFileIntoArrayMain { public static void main(String[] args) throws IOException, ClassNotFoundException { String fileName= "C:\\Users\\Arpit\\Desktop\\TxtFiles\\tempObj.txt"; ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(fileName)); int[] intArr = (int[])inputStream.readObject(); System.out.println("Array: "+Arrays.toString(intArr)); } } |
Output
1 2 3 |
Array: [1, 2, 3, 4, 5] |
That’s all about how to write array to File in Java.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.