问题
Closed question please delete!
回答1:
While I suggested in my comment that you use a BufferedWriter, I think it is easier to use Files.write.
With that, your outputPGToFile() would look like this:
private static void outputPGToFile() {
try {
Files.write(Paths.get("PostgradStudent.csv"),
Arrays.stream(PGstudentArray).map(Object::toString).collect(Collectors.toList()),
StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
(You need to add the appropriate imports)
If you really need to use the old, low-level java.io things, you can use this:
private static void outputPGToFile() {
try (FileWriter fw = new FileWriter(new File("PostgradStudent.csv"));
BufferedWriter bw = new BufferedWriter(fw)) {
for (PostGraduateStudent student : PGstudentArray) {
bw.write(student.toString());
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
The try-with-resources will make sure that the both the FileWriter and the BufferedWriter are closed, even when an exception occurs.
来源:https://stackoverflow.com/questions/58484655/java-obj-array-to-file