import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
public class test2 {
static JAXBContext jc;
static {
try {
jc = JAXBContext.newInstance(stus.class);
} catch (JAXBException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
writeZip();
readZip();
}
public static void writeZip() {
ZipOutputStream zos = null;
try {
Marshaller u = jc.createMarshaller();
zos = new ZipOutputStream(new FileOutputStream("d:\\1.zip"));
// ------------------------------------
zos.putNextEntry(new ZipEntry("1.xml"));
stus stus = new stus();
stu stu = new stu();
stu.pet.add("y1");
stu.pet.add("x2");
stus.stu.add(stu);
stu = new stu();
stu.pet.add("y2");
stu.pet.add("x1");
stu.pet.add("z3");
stus.stu.add(stu);
u.marshal(stus, zos);
// ------------------------------------
zos.putNextEntry(new ZipEntry("2.xml"));
stus = new stus();
stu = new stu();
stu.pet.add("y1");
stu.pet.add("x2");
stus.stu.add(stu);
stu = new stu();
stu.pet.add("y2");
stu.pet.add("x1");
stu.pet.add("z3");
stu.pet.add("a5");
stus.stu.add(stu);
u.marshal(stus, zos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != zos) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void readZip() {
ZipFile file = null;
try {
file = new ZipFile("d:\\1.zip");
Unmarshaller u = jc.createUnmarshaller();
ZipEntry entry = file.getEntry("1.xml");
stus stus = (stus) u.unmarshal(file.getInputStream(entry));
for (stu stu : stus.stu) {
System.out.println(stu.pet);
}
System.out.println();
// ------------------------------------
entry = file.getEntry("2.xml");
stus = (stus) u.unmarshal(file.getInputStream(entry));
for (stu stu : stus.stu) {
System.out.println(stu.pet);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != file) {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
@XmlRootElement
class stus {
public List<stu> stu = new ArrayList<stu>();
}
class stu {
public List<String> pet = new ArrayList<String>();
}
输出结果:
[y1, x2]
[y2, x1, z3]
[y1, x2]
[y2, x1, z3, a5]
说明:
也可以使用ant.jar里apache提供的zip接口,通过设置编码可以解决.xml中文名称乱码。