您当前的位置: 首页 >  ar

柳鲲鹏

暂无认证

  • 0浏览

    0关注

    4642博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

使用代码把一个目录打包成jar

柳鲲鹏 发布时间:2021-09-07 08:42:26 ,浏览量:0

具体代码如下:


    private String javaClassPath = "";
    private byte[] readerBuffer = new byte[4096];

    private void addFileToJar(File source, JarOutputStream target) throws IOException
    {
        BufferedInputStream in = null;
        try
        {
            if (source.isDirectory())
            {
                for (File nestedFile : source.listFiles())
                {
                    addFileToJar(nestedFile, target);
                }
                return;
            }
 
            String middleName = source.getPath().replace("\\", "/").substring(javaClassPath.length());
            if (middleName.startsWith("/"))
            {
                middleName = middleName.substring(1);
            }

            JarEntry entry = new JarEntry(middleName);
            entry.setTime(source.lastModified());
            target.putNextEntry(entry);
            
            in = new BufferedInputStream(new FileInputStream(source));
            while (true)
            {
                int count = in.read(readerBuffer);
                if (count == -1)
                {
                    break;
                }
                target.write(readerBuffer, 0, count);
            }
            
            target.closeEntry();
        }
        finally
        {
            if (in != null)
            {
                in.close();
            }
        }
    }
    
    void create(final String jarDataDir, final String destDir, final File jarSrc)
    {
        try
        {
            String jarName = jarSrc.getAbsolutePath();
            jarName = jarName.substring(jarName.lastIndexOf('\\')+1);
            jarName = destDir + File.separator + jarName;
            
            javaClassPath = jarDataDir;
 
            //Manifest manifest = new Manifest();
            //manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
            //JarOutputStream target = new JarOutputStream(new FileOutputStream(destJarFile), manifest);
            
            JarOutputStream target = new JarOutputStream(new FileOutputStream(jarName));
            addFileToJar(new File(javaClassPath), target);
            
            target.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

本文假设目录下已有Manifest;也可以使用注释中的代码。能不能指定某个文件呢?还真没找到办法。

关注
打赏
1665724893
查看更多评论
立即登录/注册

微信扫码登录

0.1949s