how to write an array to a file Java

Lock1618 picture Lock1618 · Dec 4, 2012 · Viewed 108k times · Source

I have been trying to write an array to a file. I know how to write integers or String to a file but to bring an array confuses me. I am using this right now:

public static void write (String file, int[]x) throws IOException{
    BufferedWriter outputWriter = null;
    outputWriter = new BufferedWriter(new FileWriter(filename));
    outputWriter.write("hi");// Here I know i cant just write x[0] or anything. Do i need 
                             //to loop in order to write the array?
    outputWriter.newLine();
    outputWriter.flush();  
    outputWriter.close();  



}

Answer

Windle picture Windle · Dec 4, 2012

Like others said, you can just loop over the array and print out the elements one by one. To make the output show up as numbers instead of "letters and symbols" you were seeing, you need to convert each element to a string. So your code becomes something like this:

public static void write (String filename, int[]x) throws IOException{
  BufferedWriter outputWriter = null;
  outputWriter = new BufferedWriter(new FileWriter(filename));
  for (int i = 0; i < x.length; i++) {
    // Maybe:
    outputWriter.write(x[i]+"");
    // Or:
    outputWriter.write(Integer.toString(x[i]);
    outputWriter.newLine();
  }
  outputWriter.flush();  
  outputWriter.close();  
}

If you just want to print out the array like [1, 2, 3, ....], you can replace the loop with this one liner:

outputWriter.write(Arrays.toString(x));