从java中的文件夹创建jar

从java中的文件夹创建jar,java,jar,Java,Jar,我需要使用java将包含许多子文件夹的文件夹转换为jar。我是java的初学者。请回复。 我需要一个java程序来将文件夹转换成.jar在编译时,您可以使用ApacheAnt之类的构建工具 <jar destfile="${dist}/lib/app.jar"> <fileset dir="${build}/classes" excludes="**/Test.class" /> <fileset dir="${src}/resources"/>

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

在编译时,您可以使用ApacheAnt之类的构建工具

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

对于运行时-试试这个。这对我有用。 对其他人来说,这是我第一次尝试。请发表您的评论,因为我可能在这里出错:)

public类CreateJar{
公共静态void main(字符串[]args)引发IOException{
字符串filePath=“/src”;
List fileEntries=new ArrayList();
GetAllFileName(新文件(文件路径)、文件条目);
JarOutputStream=newjaroutputstream(newfileoutputstream(新文件(“a.jar”));
用于(文件:fileEntries){
putNextEntry(新的ZipEntry(file.getAbsolutePath());
write(getBytes(文件));
jarStream.closeEntry();
}
jarStream.close();
}
私有静态字节[]getBytes(文件){
byte[]buffer=新字节[(int)file.length()];
BufferedInputStream bis=null;
试一试{
bis=新的BufferedInputStream(新文件输入流(文件));
//通读
while((bis.read(buffer,0,buffer.length))!=-1){
}
}catch(filenotfounde异常){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}最后{
试一试{
二、关闭();
}捕获(IOE异常){
e、 printStackTrace();
}
}
返回缓冲区;
}
私有静态void GetAllFileName(文件、列表){
if(file.isFile()){
列表。添加(文件);
}否则{
对于(文件file1:File.listFiles()){
GetAllFileName(文件1,列表);
}
}
}
}

-检查此项。。。如果你不希望它是可执行的,就不要添加清单文件…将其打包为rar,将其重命名为jar.Program以将文件夹转换为jar:
${JAVA_HOME}/bin/jar
你在构建时还是在运行时需要它?OP正在寻找构建时解决方案,而不是运行时解决方案。但他提到-“我需要一个java程序将一个文件夹转换成.jar”?投票人应该说明原因,否则我怎么知道这里的问题?我希望社区是透明的,但我确实提到OP在问其他问题-因此是投票人。看看评论。
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);
        }
    }
}
}