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

具体代码如下:

 
    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;也可以使用注释中的代码。能不能指定某个文件呢?还真没找到办法。

上一篇:使用PyInstaller把Python脚本打包成exe


下一篇:eclipse luna maven失效的原因