Javaオブジェクトの圧縮、解凍
4002 ワード
1 Javaオブジェクトをファイルに圧縮する:
2 Javaオブジェクトをファイルから読み出す
使用するUserクラス
import java.io.FileOutputStream;
import java.io.File;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
public class ZipObject {
public static void main(String[] args) {
User Jlee = new User();
Jlee.setId(new Long(1));
Jlee.setUsername("JLee");
Jlee.setPassword("111");
User user = new User();
user.setId(new Long(2));
user.setUsername(" ");
user.setPassword("123");
System.out.println(" ...");
try {
FileOutputStream fos = new FileOutputStream(new File("user.dat"));
GZIPOutputStream gos = new GZIPOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(gos);
// Java
oos.writeInt(2) ;
// Java
oos.writeObject(Jlee);
oos.writeObject(user);
oos.flush();
oos.close();
gos.close();
fos.close();
System.out.println(" ");
} catch (IOException e) {
System.out.println(" ");
e.printStackTrace();
}
}
}
2 Javaオブジェクトをファイルから読み出す
import java.io.FileInputStream;
import java.io.File;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
public class UnzipObject {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream(new File("user.dat"));
GZIPInputStream gis = new GZIPInputStream(fis);
ObjectInputStream ois = new ObjectInputStream(gis);
System.out.println(" ...");
// Java
int count = ois.readInt() ;
for(int i=0;i<count;i++){
//
User Jlee = (User) ois.readObject();
System.out.println(Jlee);
}
ois.close();
gis.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
使用するUserクラス
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 5968179219405462308L;
private Long id;
private String username;
private String password;
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 toString() {
StringBuilder sb = new StringBuilder();
sb.append("id=").append(id);
sb.append("; username=").append(username);
sb.append("; password=").append(password);
return sb.toString();
}
}