我正在创建一个包含媒体项目的图书馆,例如dvds或视频游戏,并保存媒体项目列表的文件。我必须创建一个方法,可以读取保存文件中的数据,重新创建媒体项,并将它们放入列表中。我正在考虑对其进行标记,但我无法弄清楚如何开始它。有什么建议?我正在使用java。每个媒体项都包含字符串标题,字符串格式,布尔借用,字符串名称和字符串日期。这个方法将用于在启动程序时加载保存文件。
答案 0 :(得分:0)
您可以使用序列化将数据保存到文件并将其读回。虽然你不能阅读文本。
public class MediaSave {
public static class Media implements Serializable{
/**
*
*/
private static final long serialVersionUID = 7452860232014574705L;
public String title;
public String format;
public Boolean borrowed;
public String name;
public Date date;
protected Media(String title, String format, Boolean borrowed,
String name, Date date) {
super();
this.title = title;
this.format = format;
this.borrowed = borrowed;
this.name = name;
this.date = date;
}
public String toString(){
return title + " " + format + " " + borrowed + " " + name + " " + " " + date ;
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException{
Media[] media = new Media[4];
media[0] = new Media("Avatar1", "dvd",true, "jon1", new Date());
media[1] = new Media("Avatar2", "dvd",true, "jon2", new Date());
media[2] = new Media("Avatar3", "dvd",true, "jon3", new Date());
media[3] = new Media("Avatar4", "dvd",true, "jon4", new Date());
Path p = Paths.get("resources/media.txt");
File f = p.toFile();
if(!f.exists()){
f.createNewFile();
}
try(ObjectOutputStream writer = new ObjectOutputStream(new FileOutputStream(f))){
writer.writeInt(media.length);
for(Media m : media){
writer.writeObject(m);
}
}
try(ObjectInputStream reader = new ObjectInputStream(new FileInputStream(f))){
int cnt = reader.readInt();
for(int i =0 ; i != cnt;i++){
Media m=(Media)reader.readObject();
System.out.println(m.toString());
}
}
}
}