Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
462 views
in Technique[技术] by (71.8m points)

how to write an array to a file Java

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();  



}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...