0

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?

3
  • duplicate :stackoverflow.com/questions/7608704/… Commented Jul 23, 2013 at 11:43
  • Even running the javac command using Runtime class it is possible. Commented 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 runtime Commented Jul 23, 2013 at 12:11

1 Answer 1

0

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());
        }
}

}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.