how to write an array to a file Java
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));
You can use the ObjectOutputStream
class to write objects to an underlying stream.
outputStream = new ObjectOutputStream(new FileOutputStream(filename));
outputStream.writeObject(x);
And read the Object
back like -
inputStream = new ObjectInputStream(new FileInputStream(filename));
x = (int[])inputStream.readObject()
If you're okay with Apache commons lib
outputWriter.write(ArrayUtils.join(array, ","));
Just loop over the elements in your array.
Ex:
for(int i=0; numOfElements > i; i++)
{
outputWriter.write(array[i]);
}
//finish up down here
private static void saveArrayToFile(String fileName, int[] array) throws IOException {
Files.write( // write to file
Paths.get(fileName), // get path from file
Collections.singleton(Arrays.toString(array)), // transform array to collection using singleton
Charset.forName("UTF-8") // formatting
);
}