Moon Light Box

Time is Money

Java - Serializable

| Comments

When program is executed, it will be loaded into memory.
And we cannot access the data directly in memory.
If you want to save the data to a file, we can use Serializable interface.

public class Food implements Serializable {
    private String name = "";
    private int price = 0;
    
    public Food(String name, int price) {
        this.name = name;
        this.price = price;
    }
}

public class FoodToFile {
    public static void main(String args[]) {
        Food mFood = new Food("rice", "100");
        
        try {
            FileOutputStream mFileOutputStream = new FileOutputStream("Food.txt");
            ObjectOutputStream mObjectOutputStream = new ObjectOutputStream(mFileOutputStream);
            mObjectOutputStream.writeObject(mFood); 
            mObjectOutputStream.close();
            mFileOutputStream.close();
        } catch (IOException ie) {
            System.err.println(e);
        }
    }
}

Comments

comments powered by Disqus