从 java 中的文件夹创建 jar

Create jar from a folder in java

我需要使用 java 将包含许多子文件夹的文件夹转换为 jar。我是 java 的初学者。请回复。 我需要一个 java 程序来将文件夹转换为 .jar

对于编译时间,您可以使用 Apache Ant 等构建工具。

<jar destfile="${dist}/lib/app.jar">
    <fileset dir="${build}/classes" excludes="**/Test.class" />
    <fileset dir="${src}/resources"/>
</jar>

对于运行时 - 试试这个。它对我有用。 对于其他人 - 这是我的第一次尝试。请 post 你的评论,因为我在这里可能是错误的:)

public class CreateJar {

public static void main(String[] args) throws IOException {
    String filePath = "/src";
    List<File> fileEntries = new ArrayList<>();
    getAllFileNames(new File(filePath), fileEntries);
    JarOutputStream jarStream = new JarOutputStream(new FileOutputStream(new File("a.jar")));
    for(File file : fileEntries){
        jarStream.putNextEntry(new ZipEntry(file.getAbsolutePath()));
        jarStream.write(getBytes(file));
        jarStream.closeEntry();
    }
    jarStream.close();
}

private static byte[] getBytes(File file){
    byte[] buffer = new byte[(int) file.length()];
    BufferedInputStream bis = null;
    try {
        bis = new BufferedInputStream(new FileInputStream(file));
        //Read it completely
        while((bis.read(buffer, 0, buffer.length))!=-1){
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        try {
            bis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return buffer;
}

private static void getAllFileNames(File file,List<File> list){
    if(file.isFile()){
        list.add(file);
    }else{
        for(File file1 : file.listFiles()){
            getAllFileNames(file1, list);
        }
    }
}
}