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

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



}

最佳答案

就像其他人说的那样,您可以循环遍历数组并逐个打印出元素。为了使输出显示为数字而不是您看到的“字母和符号”,您需要将每个元素转换为字符串。因此,您的代码将如下所示:

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

09-26 13:23
查看更多