问题
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();
}
回答1:
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));
回答2:
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()
回答3:
If you're okay with Apache commons lib
outputWriter.write(ArrayUtils.join(array, ","));
回答4:
Just loop over the elements in your array.
Ex:
for(int i=0; numOfElements > i; i++)
{
outputWriter.write(array[i]);
}
//finish up down here
回答5:
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
);
}
回答6:
If the result is for humans to read and the elements of the array have a proper toString()
defined...
outputString.write(Arrays.toString(array));
来源:https://stackoverflow.com/questions/13707223/how-to-write-an-array-to-a-file-java