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). You could use a try-with-resources
to do it for you
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
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
.
{
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).
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.