简体   繁体   中英

Writing data from a List field to a .txt file in Java

I have just completed the following program -

//interface IFile

package zad;

public interface IFile {
    void readFromFile();
}

//class Student

package zad;

public class Student implements Comparable {
    private String studentName;
    private int facNum, studentPoints;

    public Student(int facNum, String studentName, int studentPoints) {
        this.facNum = facNum;
        this.studentName = studentName;
        this.studentPoints = studentPoints;
    }

    public void setFacNum(int facNum) {
        this.facNum = facNum;
    }

    public int getFacNum() {
        return facNum;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentPoints(int studentPoints) {
        this.studentPoints = studentPoints;
    }

    public int getStudentPoints() {
        return studentPoints;
    }

    public boolean equals(Object o) {
        if(o instanceof Student && ((Student) o).getFacNum() == this.facNum) {
            return true;
        } else {
            return false;
        }
    }

    public String toString() {
        return ("FacNum = " + facNum + ", name = " + studentName 
                + ", points = " + studentPoints );
    }

    public int compareTo(Object o) {
        return Integer.compare(this.facNum, ((Student)o).getFacNum());
    }



}

//class StudentsGroup

package zad;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class StudentsGroup implements IFile, Comparable {
    private String groupName;
    private List<Student> studentsList = new ArrayList<Student>();

    public StudentsGroup(String groupName) {
        this.groupName = groupName;
    }

    public void printArrayList() {
        for(Student o : studentsList)
            System.out.println(o);
    }

    public int compareTo(Object o) {
        if(getTotalPoints(studentsList) > getTotalPoints(((StudentsGroup)o).studentsList))
            return 1;
        else if(getTotalPoints(studentsList) < getTotalPoints(((StudentsGroup)o).studentsList))
            return -1;
        else 
            return 0;
    }

    public List getList() {
        return studentsList;
    }

    public static int getTotalPoints(List<Student> studentsList1) {
        int totalPoints = 0;
        for(Student o : studentsList1) {
            totalPoints += o.getStudentPoints();
        }
        return totalPoints;
    }

    public void sortByPoints() {
        Collections.sort(studentsList);
    }

    public void readFromFile() {
        Scanner sc;
        try {
            sc = new Scanner(new File(groupName));
            while(sc.hasNext()) {
                int facNum = sc.nextInt();
                String studentName = sc.next();
                int studentPoints = sc.nextInt();

                Student object = new Student(facNum, studentName, studentPoints);
                studentsList.add(object);
            }
        sc.close(); 
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String toString() {
        return "StudentsGroup [groupName=" + groupName + ", studentsList=" + studentsList + "]";
    }
}

//class main

package zad;

import java.io.FileNotFoundException;

public class demo {

    public static void main(String[] args) throws FileNotFoundException {
        StudentsGroup studentsGroup1 = new StudentsGroup("D://test.txt");
        StudentsGroup studentsGroup2 = new StudentsGroup("D://test2.txt");
        studentsGroup1.readFromFile();
        studentsGroup2.readFromFile();
        studentsGroup1.printArrayList();
        studentsGroup1.sortByPoints();
        studentsGroup1.printArrayList();

        int compareResult = studentsGroup1.compareTo(studentsGroup2);

        switch(compareResult) {
            case 0: System.out.println("The two lists are equal by points.");
                    break;
            case 1: System.out.println("The first list is larger than the second.");
                    break;
            case -1: System.out.println("The first list is smaller than the second.");
                    break;
        }
    }

}

In general, it makes an object from class StudentsGroup , reads from a file and adds to an ArrayList field, as objects of another class - Student .

How should I implement a method to write that data to a new file? Any thoughts on that?

Note: also, if possible, I would like some tips on my coding to help me write better code. Am I doing something completely wrong or unnecessary in my program? The method getTotalPoints needs to be declared as static, so that is not discussed.

UPDATE:

When I try to write the data to a file with the following code:

FileOutputStream out = new FileOutputStream("D://test3.txt"); 
ObjectOutputStream oout = new ObjectOutputStream(out); 
for(Student o : studentsList)
    oout.writeObject(o);
out.close();
oout.close();

I get an error:

Exception in thread "main" java.io.NotSerializableException: zad.Student
    at java.io.ObjectOutputStream.writeObject0(Unknown Source)
    at java.io.ObjectOutputStream.writeObject(Unknown Source)
    at zad.StudentsGroup.writeToFile(StudentsGroup.java:80)
    at zad.demo.main(demo.java:27)

Am I doing something wrong?

According to the documentation for ObjectOutputStream, the writeObject method throws a NotSerializableException because Students does not implement Serializable.

NotSerializableException - Some object to be serialized does not implement the java.io.Serializable interface.

Update your class signature to the following and implement any methods required by Serializable.

public class Student implements Comparable, Serializable

By using the ObjectOutputStream.writeObject method you have no control over the output. If you want to control how the content is actually output to the file you'll want to look into an alternative writer. Look into examples of using BufferedWriter. You could then pass Student.toString() to the writer and control the way in which the data shows up. For instance, your toString() method in Student could output field1 + "\\t" + field2 + "\\t" + field3 + "\\t" + field4 - and you'd essentially have a tab-delimited file that you could then, for instance, import into Excel.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM