我已经创建了.dat文件,使用我的对象类上的implements Serializable
来保存对象的arraylist。
我有两个类成员和样式,我想将它们保存到.List文件中的arrayList中,我已经完成了所有这些工作..
我创建了一个ReadData类,它将fileLocation作为参数。然后有这些方法
public boolean load() {
public boolean save() {
public ArrayList<Member> getMembers(){
public boolean add(Object [] member) {
load方法只接受.dat文件中的所有内容并将其放入arraylist中 并保存方法只保存arraylist。像这样:(只是尝试捕捉;))
/* load Method */
FileInputStream fileIn = new FileInputStream(fileLocation);
ObjectInputStream in = new ObjectInputStream(fileIn);
this.objects = (ArrayList<Member>) in.readObject(); // <-- That Member needs to be generic also..
/* save Method */
File yourFile = new File(fileLocation);
yourFile.createNewFile();
fileOut = new FileOutputStream(fileLocation, false);
out = new ObjectOutputStream(fileOut);
out.writeObject(objects);
而不是每次都创建一个新类,而是考虑创建一个适用于所有内容的泛型类。所以我可以使用这样的东西:
ReadData membersFile = new ReadData("members.dat", new Member());
ReadData stylesFile = new ReadData("styles.dat", new Style());
所以,当成员对象来自参数时,我在ReadData类中的arraylist将是ArrayList<Member>
,而当它的样式时,ArrayList<Style>
。
有人可以帮我这么做吗?还是帮助我以其他方式实现这一目标?
答案 0 :(得分:3)
你是如此接近这一点。以下是使此通用的相关代码。不幸的是,java序列化对象不能识别类型,因此您需要将对象转换为静态。
public <T> ArrayList<T> ReadData(String filename, T type) {
.....
this.objects = (ArrayList<T>) in.readObject();
.....
}
如果您想了解有关泛型编程的更多信息,oracle已经编写了一个可靠的tutorial,它将向您展示基础知识。
除了更改类的方法签名之外,还需要使类通用。
public class ReadDataMembers<T> {
public ReadDataMember(String filename) {
}
}
您不需要通过构造函数传递类型,但可以使用以下语法
ReadDataMembers rdm = new ReadDataMembers<Member>("member.dat");