在java中可以在运行时创建一个hashmap / tree结构,并仅在运行时将其保存为文件/ Java文件。并将其保存为java文件或编译文件,并将其用于其他一些应用程序。这是一种可能的情况吗?
答案 0 :(得分:0)
我们可以在运行时将java对象保存并检索到文件中。
保存对象应该实现Serializable接口
class Person实现Serializable {
String firstName;
String lastName;
public Person(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName
+ "]";
}
}
public class HashMapSerialization {
public static void main(String[] args) throws Exception {
Map<String, Person> map = new HashMap<String, Person>();
map.put("1", new Person("firstName1","lastName1"));
map.put("2", new Person("firstName2","lastName2"));
map.put("3", new Person("firstName3","lastName3"));
FileOutputStream fos = new FileOutputStream("person.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(map);
oos.close();
}
}
public class HashMapDeSerialization {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("person.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Map<String, Person> anotherMap = (Map) ois.readObject();
ois.close();
Set keySet = anotherMap.keySet();
for (Object object : keySet) {
Person person = anotherMap.get((String)(object));
System.out.println(person.toString());
}
}
}