This example demonstrates how to compress a Java object. We compress the Java object using GZIPOutputStream
, pass it to ObjectOutputStream
to write the object into an external file. The object we are going to compress will be represented by the User
object. We need to make the User
object serializable, so it must implement the java.io.Serializable
interface. You can see the complete code snippet below.
package org.kodejava.util.zip;
import org.kodejava.util.support.User;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.zip.GZIPOutputStream;
public class ZipObjectDemo {
public static void main(String[] args) {
User admin = new User();
admin.setId(1L);
admin.setUsername("admin");
admin.setPassword("secret");
admin.setFirstName("System");
admin.setLastName("Administrator");
User foo = new User();
foo.setId(2L);
foo.setUsername("foo");
foo.setPassword("secret");
foo.setFirstName("Foo");
foo.setLastName("Bar");
System.out.println("Zipping....");
System.out.println(admin);
System.out.println(foo);
File file = new File("user.dat");
try (FileOutputStream fos = new FileOutputStream(file);
GZIPOutputStream gos = new GZIPOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(gos)) {
oos.writeObject(admin);
oos.writeObject(foo);
oos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package org.kodejava.util.support;
import java.io.Serializable;
public class User implements Serializable {
private Long id;
private String username;
private String password;
private String firstName;
private String lastName;
public User() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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 "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}
Running the code snippet will give us the following output:
Zipping....
User{id=1, username='admin', password='secret', firstName='System', lastName='Administrator'}
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