如何将文件夹压缩成JAR文件

[复制链接]
查看11 | 回复1 | 2009-8-25 08:54:51 | 显示全部楼层 |阅读模式
先解压,然后压缩为zip,然后将后缀名改为jar。本java小工具是可实现批量压缩文件包为jar包,核心代码如下:/**
* zip压缩
* @param parentDirPath 要压缩文件夹的父文件夹
* @param targetPath 目标文件夹
*/
private static void zipDirectory(String parentDirPath,String targetPath)
{
try {
File dirFile=new File(parentDirPath);
File[] listArr = dirFile.listFiles();
for (File childFile: listArr) {
//File childFile=new File(child);
if(childFile.isDirectory())
{
if(list.size()>0)
list.clear();
byte b[] = new byte[128];
//压缩文件的保存路径
String zipFile =targetPath+File.separator+childFile.getName()+".jar";
//压缩文件目录
String filepath =childFile.getAbsolutePath()+File.separator;
List fileList = allFile(filepath);
FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
//使用输出流检查
CheckedOutputStream cs = new CheckedOutputStream(fileOutputStream, new CRC32());
//声明输出zip流
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
cs));
for (int i = 0; i < fileList.size(); i++) {
InputStream in = new FileInputStream((String)fileList.get(i));
String fileName = ((String)(fileList.get(i))).replace(File.separatorChar,'/');
System.out.println("ziping " + fileName);
String tmp= childFile.getName()+"/";
fileName = fileName.substring(fileName.lastIndexOf(tmp)+childFile.getName().length()+1);
ZipEntry e = new ZipEntry(fileName);
out.putNextEntry(e);
int len = 0;
while((len = in.read(b)) != -1) {
out.write(b,0,len);
}
out.closeEntry();
}
out.close();
System.out.println("done!");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
回复

使用道具 举报

千问 | 2009-8-25 08:54:51 | 显示全部楼层
是想做成电子书吗
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行