如何将数组写入Java文件

时间:2012-12-04 16:19:47

标签: java arrays file loops bufferedwriter

我一直在尝试将数组写入文件。我知道如何将整数或字符串写入文件但是让数组混淆了我。我现在正在使用它:

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



}

6 个答案:

答案 0 :(得分:13)

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

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

然后阅读Object回来 -

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

答案 1 :(得分:13)

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

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 :(得分:4)

如果你对Apache commons lib

没问题
outputWriter.write(ArrayUtils.join(array, ","));

答案 3 :(得分:3)

只需循环遍历数组中的元素。

例如:

for(int i=0; numOfElements > i; i++)
{
outputWriter.write(array[i]);
}
//finish up down here

答案 4 :(得分:0)

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

outputString.write(Arrays.toString(array));

答案 5 :(得分:0)

private static void saveArrayToFile(String fileName, int[] array) throws IOException {
        Files.write(Paths.get(fileName), Collections.singleton(Arrays.toString(array)), Charset.forName("UTF-8"));
}