in java is it possible to create a hashmap/ tree structure at runtime, and save it as a file/Java file at runtime only. and keep it as a java file or compiled file and use it for some other application. Is this a possible scenario?
-
duplicate :stackoverflow.com/questions/7608704/…Suresh Atta– Suresh Atta2013-07-23 11:43:40 +00:00Commented Jul 23, 2013 at 11:43
-
Even running the javac command using Runtime class it is possible.Xavier DSouza– Xavier DSouza2013-07-23 11:52:41 +00:00Commented Jul 23, 2013 at 11:52
-
Hi Suresh, no its not i have seen the question earlier. what i am asking is how to generate my file with the hashmap content , and all this at runtimeAada– Aada2013-07-23 12:11:19 +00:00Commented Jul 23, 2013 at 12:11
Add a comment
|
1 Answer
We can save and retrieve the java objects into file at run time.
Saving object should implement Serializable interface
class Person implements 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());
}
}
}