在 java 中是否可以在运行时创建 hashmap/ 树结构,并仅在运行时将其保存为文件/Java 文件。并将其保存为 java 文件或编译文件,并将其用于其他应用程序。这是可能的情况吗?
问问题
843 次
1 回答
0
我们可以在运行时将 java 对象保存和检索到文件中。
保存对象应该实现 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
+ "]";
}
}
公共类 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();
}
}
公共类 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());
}
}
}
于 2013-07-23T12:51:33.130 回答