public static void main(String[] args) throws Exception {
//分别是三个文件的输入流
InputStream in1 = new FileInputStream("E:/nomanager/test/file1.txt");
InputStream in2 = new FileInputStream("E:/nomanager/test/file2.txt");
InputStream in3 = new FileInputStream("E:/nomanager/test/file3.txt");
//分别是三个文件读取时的缓冲区大小,1024Bytes,也就是说每次读1M,假如文件1有2.5M,那就要读三次
byte[] b1=new byte[1024];
byte[] b2=new byte[1024];
byte[] b3=new byte[1024];
//每个文件读完后,用一个字符串存储文件内容
String s1="";
String s2="";
String s3="";
//下面这个while循环读文件的代码不知道你看不看得懂,我不知道该怎么写注释,你要是不懂再问我吧
int len1=0;
int len2=0;
int len3=0;
while((len1=in1.read(b1))!=-1){
s1+=new String(b1, 0, len1);
}
while((len2=in2.read(b2))!=-1){
s2+=new String(b2, 0, len2);
}
while((len3=in3.read(b3))!=-1){
s3+=new String(b3, 0, len3);
}
//定义输出流,目的地是aaa.zip
FileOutputStream fout = new FileOutputStream("E:/nomanager/test/aaa.zip");
//将三个文件的内容放进一个map里
Map<String, byte[]> datas = new HashMap<String, byte[]>();
datas.put("file1.txt", s1.getBytes());
datas.put("file2.txt", s2.getBytes());
datas.put("file3.txt", s3.getBytes());
//装饰器模式:用ZipOutputStream包装输出流,使其拥有写入zip文件的能力
ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream(fout));
//遍历
Set<String> keys = datas.keySet();
for (String key : keys) {
//下面就是循环把每个文件写进zip文件
InputStream bin = new BufferedInputStream(new ByteArrayInputStream(datas.get(key)));
byte[] b = new byte[1024];
zipout.putNextEntry(new ZipEntry(key));
int len = -1;
while ((len = bin.read(b)) !=-1) {
zipout.write(b, 0, len);
}
}
zipout.close();
}
还没有评论,来说两句吧...