如何将数组写入文件 Java [英] how to write an array to a file Java

查看:133
本文介绍了如何将数组写入文件 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();  



}

推荐答案

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

Like others said, you can just loop over the array and print out the elements one by one. To make the output show up as numbers instead of "letters and symbols" you were seeing, you need to convert each element to a string. So your code becomes something like this:

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, ....]这样的数组,你可以用这一行替换循环:

If you just want to print out the array like [1, 2, 3, ....], you can replace the loop with this one liner:

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

这篇关于如何将数组写入文件 Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆