文件输入和输出序列化

File input and Output Serialization

我只想有人评论这段代码,让我理解这段代码在做什么,它很完美,但我不明白。我知道这个网站有专业的编码人员,但到目前为止我还不知道如何调试。

请把它注释掉,让我一步步理解它的作用。

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class Serialization {
public static void main(String[] args) throws FileNotFoundException, IOException,ClassNotFoundException {
    File file = new File("students.txt");
    ArrayList<Student> psy101 = new ArrayList<Student>();

    psy101.add (new Student("Bob", 2.9));
    psy101.add(new Student("Smith", 3.9));
    psy101.add(new Student("John",4.9));
    psy101.add(new Student("Amy",10.9));


    FileOutputStream fo = new FileOutputStream(file);
    ObjectOutputStream output = new ObjectOutputStream(fo);

    for(Student s : psy101){
    output.writeObject(s);


}
output.close();
fo.close();


FileInputStream fi = new FileInputStream(file);
ObjectInputStream input = new ObjectInputStream(fi);
ArrayList<Student> psy1012 = new ArrayList<Student>();
try{
while (true){
    Student s = (Student)input.readObject();
     psy1012.add(s);
}
}catch (EOFException ex){

}
for (Student s : psy1012){
    System.out.println(s);
}

另一个class是这个,任何评论都将不胜感激。

import java.io.Serializable;

public class Student implements Serializable {
private String Name;
private double GPA;

public Student(String name, double gpa){
    this.Name = name;
    this.GPA = gpa;

}

public String getName() {
    return this.Name;
}

public String getName(String newName) {
    return(this.Name = newName);
}

public double getGPA() {
    return this.GPA;
}

public double setGPA(double newgGPA) {
    return (this.GPA = GPA);
}
@Override
    public String toString() {
        // TODO Auto-generated method stub
        return String.format("%s\t%f",this.Name,this.GPA);
    }
}

首先我可以看到你有两个 classes,

第一个class用于连载,第二个用于学生。 现在我无法逐行评论,但我会提供一些信息,以便您可以阅读更多内容。

https://docs.oracle.com/javase/tutorial/essential/io/

写入文本文件

要将文本写入文件,您可以使用 class FileWriter 打开输出流。如果该文件不存在,则会创建一个具有此名称的新空文件。如果文件已经存在,打开它会删除文件中的数据。如果要附加到文件,请在创建 FileWriter 对象时使用以下选项:

FileWriter fWriter = new FileWriter (outFile, true); class PrintWriter 具有 print()、printf() 和 println() 方法,可让我们写入文件。

这也会对你有所帮助。 http://www.cs.utexas.edu/~mitra/csSummer2009/cs303/lectures/fileIO.html

现在我相信一旦你 运行 你的代码你会注意到 students.txt 将在你的代码和控制台中包含信息,但是它会被序列化,Java 提供了一个机制,称为对象序列化,其中对象可以表示为字节序列,其中包括对象的数据以及有关对象类型和存储在对象中的数据类型的信息。

序列化对象写入文件后,可以从文件中读取并反序列化,即表示对象及其数据的类型信息和字节可用于在内存中重新创建对象。

最令人印象深刻的是整个过程是独立于 JVM 的,这意味着一个对象可以在一个平台上序列化并在完全不同的平台上反序列化。因此,请阅读以上内容,它应该有所帮助。