繁体   English   中英

如何在Java中将数组的内容输出到文本文件中?

[英]How to output the contents of an array into a text file in Java?

我想知道如何将数组的整数输出到由不同行分隔的文本文件中。 这是下面的相关代码,但是每次我运行该程序时,都会创建该文件,但不会将任何数据保存到文件本身中。

public static void printToFile(double[] gravity)throws IOException
{
    PrintWriter outputFile = new PrintWriter (new FileWriter("gravitydata.txt", true));
    for(int a = 0; a < 9; a++)
    {
         outputFile.println(gravity[a]);
    }
}

您必须close()文件(关闭PrintWriter将关闭FileWriter ,这将关闭文件)。 您可以使用try-with-resources为您做到这一点

public static void printToFile(double[] gravity) throws IOException
{
    try (PrintWriter outputFile = new PrintWriter(
            new FileWriter("gravitydata.txt", true))) {
        for(int a = 0; a < gravity.length; a++){
            outputFile.println(gravity[a]);
        }
    }
}

或较旧的finally块之类的东西

public static void printToFile(double[] gravity) throws IOException
{
    PrintWriter outputFile = new PrintWriter(
            new FileWriter("gravitydata.txt", true))
    try {
        for(int a = 0; a < gravity.length; a++){
            outputFile.println(gravity[a]);
        }
    } finally {
        outputFile.close();
    }
}

无论哪种情况,都应该使用array length属性而不是硬编码9

{
    PrintWriter outputFile = new PrintWriter (new FileWriter("gravitydata.txt", true));
    for(int a = 0; a < 9; a++)
    {
        outputFile.println(gravity[a]);
    }
    outputFile.close();

}

如果您希望利用Java 8的内置函数(以避免编写自己的文件处理和循环),则以下方法可能很好。

public static void printToFile(double[] gravity) throws IOException {
    // First, convert the double[] to a list of Strings
    final List<String> doublesAsStrings = Arrays.stream(gravity)
            .boxed() // Box it to Doubles
            .map(g -> String.valueOf(g)) // Convert each Double to a String
            .collect(Collectors.toList()); // Create a List<String>

    // Then, write the list to the file
    Files.write(new File("gravitydata.txt").toPath(), doublesAsStrings);
}

与以前的答案相比,有一些区别:

  • Files类用于写入数据,这很方便,因为它可以处理try / catch等
  • 不需要外部循环,因为流API:用于创建将要打印的字符串序列
  • 它短而紧凑;)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM