14

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

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



}
4

6 回答 6

20

您可以使用ObjectOutputStream该类将对象写入底层流。

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

并像阅读Object背面一样 -

inputStream = new ObjectInputStream(new FileInputStream(filename));
x = (int[])inputStream.readObject()
于 2012-12-04T16:21:32.240 回答
20

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

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));
于 2012-12-04T16:39:07.143 回答
4

如果你对 Apache commons lib 没问题

outputWriter.write(ArrayUtils.join(array, ","));
于 2012-12-04T16:28:24.360 回答
3

只需遍历数组中的元素。

前任:

for(int i=0; numOfElements > i; i++)
{
outputWriter.write(array[i]);
}
//finish up down here
于 2012-12-04T16:25:18.990 回答
2
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
    );
}
于 2019-02-21T14:50:12.097 回答
0

如果结果是供人类阅读并且数组的元素具有正确toString()定义的...

outputString.write(Arrays.toString(array));
于 2012-12-04T16:30:33.463 回答