如何将数组写入文件 Java

2022-09-03 08:45:50

我一直在尝试将数组写入文件。我知道如何将整数或字符串写入文件,但带来数组让我感到困惑。我现在正在使用它:

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

就像其他人说的,你可以循环访问数组并逐个打印出元素。要使输出显示为数字而不是您看到的“字母和符号”,您需要将每个元素转换为字符串。所以你的代码变成这样:

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

如果你只想像 这样打印出数组,你可以用这个衬里替换循环:[1, 2, 3, ....]

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

答案 2

可以使用该类将对象写入基础流。ObjectOutputStream

outputStream = new ObjectOutputStream(new FileOutputStream(filename));
outputStream.writeObject(x);

并像这样读回——Object

inputStream = new ObjectInputStream(new FileInputStream(filename));
x = (int[])inputStream.readObject()