在Java中将对象数组正确输出到.csv文件 [英] Outputting array of object to .csv file correctly in Java

查看:175
本文介绍了在Java中将对象数组正确输出到.csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我要完成的这个项目上,我需要一些帮助.每当我尝试输出具有以下数据字段的学生对象数组时:

I'm in need of a little help with this project I'm trying to complete. Whenever I try output my array of student objects with the data fields of:

(学生ID,名字,姓氏,出生日期,最终成绩,年级).

(Student ID, First name , Last name, Date of birth, Final mark, Grade).

我很确定它与我的toString()方法及其格式有关,也许我应该创建另一个用于输出格式的方法,而不要使用我想要的格式toString()打印到屏幕上.

I'm pretty sure it has got to do with my toString() method and the format of it, maybe I should create another method to use for the output format instead of using toString() which is the format I want to print to the screen.

我现在要发布的此问题的目标结果是让每行中的每个主题以及每条数据(例如,学生ID,名字等)都位于.csv文件或其他文件中的单独列中用Excel电子表格表示.

My goal outcome with this question I'm posting now is to have each subject in each row and each piece of data such as Student ID, First name and so on to be in separate columns in the .csv file or in other words an excel spreadsheet.

这是我的代码段,如果有人可以帮助我找出一种或两种方法将对象数组中的信息正确输出到.csv文件,将不胜感激!预先谢谢你!

Here is a snippet of my code and if someone could help me figure out a method or two to output the information within the array of objects correctly to a .csv file that would be greatly appreciated! Thank you in advance!

public class NewClass {
    public static void main(String[] args) {
        static PostGraduateStudent[] PGstudentArray;
    }

    private static void getPGStudentDetails() {

        PostGraduateStudent s1 = new PostGraduateStudent();
        s1.setName("Vasiliy", "Zaytsev");
        s1.setDateOfBirth(02, 5, 1993);
        s1.setID(25643924);
        s1.setTitle("Mr");
        s1.setEveryMark(50, 50, 50);
        s1.calcMarks();
        s1.calcGrade();
        // System.out.println(s1);

        PostGraduateStudent s2 = new PostGraduateStudent();
        s2.setName("Joseph", "Stojk");
        s2.setDateOfBirth(29, 12, 1990);
        s2.setID(32454523);
        s2.setTitle("Mr");
        s2.setEveryMark(80, 70, 60);
        s2.calcMarks();
        s2.calcGrade();
        // System.out.println(s2);

        PostGraduateStudent s3 = new PostGraduateStudent();
        s3.setName("Arkan", "Tigrovi");
        s3.setDateOfBirth(23, 10, 1992);
        s3.setID(83957293);
        s3.setTitle("Mr");
        s3.setEveryMark(60, 60, 70);
        s3.calcMarks();
        s3.calcGrade();
        // System.out.println(s3);

        PostGraduateStudent s4 = new PostGraduateStudent();
        s4.setName("Draza", "Mihailovic");
        s4.setDateOfBirth(23, 3, 1988);
        s4.setID(13121389);
        s4.setTitle("Mr");
        s4.setEveryMark(99, 98, 99);
        s4.calcMarks();
        s4.calcGrade();
        // System.out.println(s4);

        PostGraduateStudent s5 = new PostGraduateStudent();
        s5.setName("Dragana", "Mirkovic");
        s5.setDateOfBirth(10, 9, 1979);
        s5.setID(64926748);
        s5.setTitle("Mr");
        s5.setEveryMark(24, 26, 100);
        s5.calcMarks();
        s5.calcGrade();
        //System.out.println(s5);

        PostGraduateStudent s6 = new PostGraduateStudent();
        s6.setName("Stefan", "Jokic");
        s6.setDateOfBirth(10, 9, 1980);
        s6.setID(4829464);
        s6.setTitle("Mr");
        s6.setEveryMark(98, 80, 98);
        s6.calcMarks();
        s6.calcGrade();

        PGstudentArray = new PostGraduateStudent[] { s1, s2, s3, s4, s5, s6 };
    }

    private static void outputPGToFile() {
        try {
            FileOutputStream f = new FileOutputStream(new File("PostgradStudent.csv"));
            ObjectOutputStream o = new ObjectOutputStream(f);

            //Writes the objects to the file
            for(int i = 0; i < PGstudentArray.length; i++) {
                o.writeObject(PGstudentArray[i].toString());
            }

            o.close();
            f.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found");
        } catch (IOException e) {
            System.out.println("Error initialising the stream");   
        }
    }
}


//ToString function in my student class

@Override //Simple method to select format of output and output the instance variables
public String toString() {
    String output = String.format("%5d %2d-%2d-%2d %-3s %-5s %-5s %3d %2s", this.studentID, this.day_dob, this.month_dob, this.year_dob, this.title, this.firstName, this.lastName, this.marks, this.grade);
    return output;
}

这是我为研究生提供的输出示例.我无法发布图片,因为我没有10次重复,因此这里是其链接:) https://gyazo.com/f3b1d23276607b0bb1edb890e5ddafef

This is an example of the output that I get for postgrad students. I couldn't post a image because I don't have 10 reps so here's the link to it :) https://gyazo.com/f3b1d23276607b0bb1edb890e5ddafef

推荐答案

虽然我在评论中建议您使用BufferedWriter,但我认为使用Files.write更容易.

While I suggested in my comment that you use a BufferedWriter, I think it is easier to use Files.write.

这样,您的outputPGToFile()看起来应该像这样:

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)

如果您真的需要使用旧的,低级的java.io东西,则可以使用以下方法:

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();
    }
}

即使资源发生异常,try-with-resources也将确保同时关闭FileWriterBufferedWriter.

The try-with-resources will make sure that the both the FileWriter and the BufferedWriter are closed, even when an exception occurs.

这篇关于在Java中将对象数组正确输出到.csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆