如何写一个数组到一个文件中的Java [英] how to write an array to a file Java

查看:118
本文介绍了如何写一个数组到一个文件中的Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图写一个数组到一个文件中。我知道如何写整数或字符串的文件,但带来一个数组混淆了我。我用这现在:

 公共静态无效的写(字符串的文件,INT []×)抛出IOException
    BufferedWriter将outputWriter = NULL;
    outputWriter =新的BufferedWriter(新FileWriter的(文件名));
    outputWriter.write(HI); //在这里,我知道我不能只是写X [0]或任何东西。我需要
                             //循环为了写数组?
    outputWriter.newLine();
    outputWriter.flush();
    outputWriter.close();}


解决方案

与其他人一样说数组,你可以遍历和一个打印出的元素之一。为了使输出显示为数字而不是字母和符号你看,你需要每个元素转换为字符串。所以,你的code变成这样的:

 公共静态无效的写(字符串文件名,INT []×)抛出IOException
  BufferedWriter将outputWriter = NULL;
  outputWriter =新的BufferedWriter(新FileWriter的(文件名));
  的for(int i = 0; I< x.length;我++){
    // 也许:
    outputWriter.write(X [I] +);
    // 要么:
    outputWriter.write(Integer.toString(X [I]);
    outputWriter.newLine();
  }
  outputWriter.flush();
  outputWriter.close();
}

如果你只是想打印出来像数组 [1,2,3,...] ,可以取代这一个班轮循环:

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

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

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天全站免登陆