In the previous example How do I compress Java objects? we have manage to compress Java objects and stored them in file. In this example we will read the file and reconstruct the compressed objects. For the User
class you can see in the previous example mentioned above.
package org.kodejava.util.zip;
import org.kodejava.util.support.User;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.zip.GZIPInputStream;
public class UnzipObjectDemo {
public static void main(String[] args) {
File file = new File("user.dat");
try (FileInputStream fis = new FileInputStream(file);
GZIPInputStream gis = new GZIPInputStream(fis);
ObjectInputStream ois = new ObjectInputStream(gis)) {
User admin = (User) ois.readObject();
User foo = (User) ois.readObject();
System.out.println("Admin = [" + admin + "]");
System.out.println("Foo = [" + foo + "]");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Running the code snippet above will give us the following output:
Admin = [User{id=1, username='admin', password='secret', firstName='System', lastName='Administrator'}]
Foo = [User{id=2, username='foo', password='secret', firstName='Foo', lastName='Bar'}]
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024