[英]How to output the contents of an array into a text file in Java?
I want to know how to output the integers of an array into a text file separated by different lines. 我想知道如何将数组的整数输出到由不同行分隔的文本文件中。 This is the pertinent code below, but every time I run the program, the file is created but no data is saved into the file itself.
这是下面的相关代码,但是每次我运行该程序时,都会创建该文件,但不会将任何数据保存到文件本身中。
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]);
}
}
You have to close()
the file (closing the PrintWriter
will close the FileWriter
which will close the file). 您必须
close()
文件(关闭PrintWriter
将关闭FileWriter
,这将关闭文件)。 You could use a try-with-resources
to do it for you 您可以使用
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]);
}
}
}
or the older finally
block and something like 或较旧的
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();
}
}
in either case you should use the array length
property instead of hard-coding 9
. 无论哪种情况,都应该使用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();
}
The following approach can be good if you wish to utilize the built-in functions from Java 8 (to avoid writing your own file handling and looping). 如果您希望利用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);
}
There are a few differences compared to the previous answers: 与以前的答案相比,有一些区别:
Files
class is used to write the data which is convenient since it handles try/catch etc Files
类用于写入数据,这很方便,因为它可以处理try / catch等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.