【问题标题】:Create jar from a folder in java从java中的文件夹创建jar
【发布时间】:2015-09-09 05:55:01
【问题描述】:

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

【问题讨论】:

标签: java jar


【解决方案1】:

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

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

对于运行时 - 试试这个。它对我有用。 对于其他人 - 这是我第一次尝试。请张贴您的 cmets,因为我在这里可能是错的:)

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);
        }
    }
}
}

【讨论】:

  • OP 正在寻找构建时解决方案,而不是运行时解决方案。
  • 但他提到-“我需要一个java程序来将文件夹转换为.jar”?
  • 投反对票的人应该说明原因,否则我怎么会知道这里的问题?我希望 SO 社区是透明的
  • 但我确实提到了 OP 在问别的问题 - 因此投反对票。
  • 看看 cmets。
猜你喜欢
  • 1970-01-01
  • 2015-05-22
  • 2015-04-24
  • 2012-07-14
  • 1970-01-01
  • 2019-01-22
  • 2011-06-03
  • 2012-05-19
  • 2021-11-19
相关资源
最近更新 更多