gpt4 book ai didi

java - 从java中的文本文件中读取对象数据

转载 作者:行者123 更新时间:2023-11-30 11:44:32 25 4
gpt4 key购买 nike

我正在做关于 java I/O 数据的作业,问题是我不允许使用对象序列化从二进制文件加载数据。

作业要求如下:

Persistence, writing objects to file and reading objects from file (Text format)

• All objects should be written to a single file in a text format
• All objects should be read form the same file
• You should use JFileChooser

我有 3 个类:UnitAssessmentTask

Assessment 类是抽象的,而 IndividualAssessmentGroupAssessment 是具体的子类。

Unit 有一个 Assessment 的集合,Assessment 有一个 Task 的集合。

我可以使用 FileWriter 将所有数据保存到一个文本文件,但我不知道如何将文本文件的每一行读入正确的 Assessment 类。

我的意思是您如何识别哪一行是IndividualAssessmentGroupAssessment 类。

这是我试过但不起作用的代码:

BufferedReader bf = new BufferedReader(file);
While (bf.readLine != null){
Unit u = new Unit(bf);
diary.add(u);
try{
Assessment a = new IndividualAssessment(bf);
} catch (IOException ex){
Assessment a = new GroupAssessment(bf);
}
u.add(a);
Task t = new Task(bf);
a.add(t);

最佳答案

您可能应该先将读取到的行的内容存储在一个字符串对象中。所以它看起来像这样:

String line = bf.readLine();
while(line != null) {
// Add code to look at your line to figure out what kind of object it
// represents. For example you could add a one character prefix to each
// line when you write it to specify which object it is ('U', 'A' or 'T').
// Based on that, you can call a constructor of the appropriate object that
// takes a String as input. Then let the constructor deal with parsing the
// line for the object it represents. This way you don't end up with some
// massive parsing routine.

char code = line.charAt(0);
if(code == 'T') {
Task task = new Task();
task.initFromString(line.sustring(1));
... Do something with your task
}
else if(code == ...) {
}

line = bf.readLine(); // Read the next line
}

定义一些你所有的对象都应该实现的接口(interface):

public interface TextExportable {
public char getClassIdentifier();
public void initFromString(String s);
}

我不确定你的对象是什么样子的,但让我们举个例子:

public class Task implements TextExportable {
private String name;

public Task() {} // For the pseudo-serialization

public Task(String name) { // For creating the object by hand
this.name = name;
}

public char getClassIdentifier() {
return 'T';
}

public String toString() {
return getClassIdentifier()+name;
}

public void initFromString(String line) {
this.name = line;
// Here, you would need extra parsing if you have more than one attribute
// and dissect the line
}
}

关于java - 从java中的文本文件中读取对象数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10758319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com