如何建立java. jar包_如何使用JarOutputStream创建JAR文件?

事实证明,这JarOutputStream有三个未记载的怪癖:目录名称必须以“/”斜杠结尾。

路径必须使用'/'斜杠,而不是'\'

条目不能以“/”斜杠开头。

以下是创建Jar文件的正确方法:public void run() throws IOException{

Manifest manifest = new Manifest();

manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");

JarOutputStream target = new JarOutputStream(new FileOutputStream("output.jar"), manifest);

add(new File("inputDirectory"), target);

target.close();}private void add(File source, JarOutputStream target) throws IOException{

BufferedInputStream in = null;

try

{

if (source.isDirectory())

{

String name = source.getPath().replace("\\", "/");

if (!name.isEmpty())

{

if (!name.endsWith("/"))

name += "/";

JarEntry entry = new JarEntry(name);

entry.setTime(source.lastModified());

target.putNextEntry(entry);

target.closeEntry();

}

for (File nestedFile: source.listFiles())

add(nestedFile, target);

return;

}

JarEntry entry = new JarEntry(source.getPath().replace("\\", "/"));

entry.setTime(source.lastModified());

target.putNextEntry(entry);

in = new BufferedInputStream(new FileInputStream(source));

byte[] buffer = new byte[1024];

while (true)

{

int count = in.read(buffer);

if (count == -1)

break;

target.write(buffer, 0, count);

}

target.closeEntry();

}

finally

{

if (in != null)

in.close();

}}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值