Java学习:一个压缩文件的例子
2008-01-05 20:11:01 来源:WEB开发网/**
* @(#) ZipFile.java
*
* Copyright 2004 Opensource Develop Team. All rights reserved.
*/
package com.opensource.zip;
import java.io.File;
import java.io.FileInputStream;
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.ZipOutputStream;
/**
* 在CSDN帖子http://community.csdn.net/EXPert/topic/3316/3316352.xml?temp=.2301905中看到
* 关于ZIP压缩文件的问题,在该类中主要演示在ZIP压缩中可以不把文件路径压缩进去
*
* @author O.D.T
* @version 1.0 04/08/27
*/
public class ZipFile
{
public static void main(String[] args)
{
ArrayList fileNames = new ArrayList(); // 存放文件名,并非含有路径的名字
ArrayList files = new ArrayList(); // 存放文件对象
try
{
FileOutputStream fileOut = new FileOutputStream("E:/ZipOutOfPath.zip");
ZipOutputStream outputStream = new ZipOutputStream(fileOut);
File rootFile = new File("E:/temp");
listFile(rootFile, fileNames, files);
for (int loop=0; loop<files.size(); loop++)
{
FileInputStream fileIn = new FileInputStream((File)files.get(loop));
outputStream.putNextEntry(new ZipEntry((String)fileNames.get(loop)));
byte[] buffer = new byte[1024];
while (fileIn.read(buffer) != -1)
{
outputStream.write(buffer);
}
outputStream.closeEntry();
fileIn.close();
}
outputStream.close();
}
catch (IOException ioe)
{
ioe.PRintStackTrace();
}
}
static void listFile(File parentFile, List nameList, List fileList)
{
if (parentFile.isDirectory())
{
File[] files = parentFile.listFiles();
for (int loop=0; loop<files.length; loop++)
{
listFile(files[loop], nameList, fileList);
}
}
else
{
fileList.add(parentFile);
nameList.add(parentFile.getName());
}
}
}
更多精彩
赞助商链接