Java obj array to file

北城余情 提交于 2019-12-25 00:34:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!