I'm working on a java project and using Eclipse with JDK 1.7. I have 2-D array of object type as Object[][] array
. I wish to store the contents (export) of array to a csv file (each value in a separate column for each row) on the disk. Here is the code I'm trying:
FileOutputStream fos = new FileOutputStream("newFile.csv");
ObjectOutputStream oos = new ObjectOutputStream(fos);
for(int i=0;i<array.length;i++)
{
for(int j=0;j<array[0].length;j++)
{
oos.writeObject(array);
oos.writeObject(",");
}
}
oos.close();
The output stored in file newFile.csv
is as follows:
¬íur[[Ljava.lang.Object;¿ûSäkÛÊxpur[Ljava.lang.Object;ÎXŸs)lxpt1t1tClosedt100.00000000t
0.00000000uq~t2t1tClosedt200.00000000t100.00000000uq~t3t1tClosedt100.00000000t50.00000000t q~q~q~q~q~q~q~q~q~q~q~q~q~q~q~q~q~q~q~q~q~q~q~q~q~q~q~q~
which is some garbage value. I need help to figure out what is wrong in this program (how to convert object into a string before storing, this is what I'm guessing the error is), and how to resolve the issue.
I found a help on http://www.tutorialspoint.com/java/io/objectinputstream_readobject.htm but it deals with byte[]
and String
, not with 2-D object array. Similarly, http://www.mkyong.com/java/how-to-write-to-file-in-java-fileoutputstream-example/ deals with byte[]
only. I have also found a solution at Java - How to write ArrayList Objects into txt file?, where ArrayList<String> MenuArray = new ArrayList<String>();
is used instead of 2-D object array, and also the solution is not complete. I also find a help at Using FileUtils in eclipse
I'm getting the similar error.
The solution says use:
FileUtils.writeLines(new File("input.txt"), array);
However, I receive an error that method writeLine(File, Collection<>) is not applicable for WriteLine(File, Object[][])
.
Further a solution in ADO.NET exists for reading csv file and store data in 2-D array at Reading a csv file and storing the data in a 2-D object array, but I need the other way and also solution in not for Java.
Both the methods I used are not working. Please note my 2-D array is of Object
type not String
. Any help is appreciated.