[英]Create jar from a folder in java
I need to convert a folder, that contains many sub folders to jar, using java.我需要使用 java 将包含许多子文件夹的文件夹转换为 jar。 I'm a beginner in java.我是java初学者。 Please reply.请回复。 I need a java program to convert a folder into a .jar我需要一个 Java 程序来将文件夹转换为 .jar
For complie time, you can use build tools like Apache Ant.对于编译时间,您可以使用 Apache Ant 之类的构建工具。
<jar destfile="${dist}/lib/app.jar">
<fileset dir="${build}/classes" excludes="**/Test.class" />
<fileset dir="${src}/resources"/>
</jar>
For runtime - Try this.对于运行时 - 试试这个。 It worked for me.它对我有用。 For others - this is my first attempt at it.对于其他人 - 这是我第一次尝试。 Please post your comments because i can be wrong here:)请发表您的评论,因为我在这里可能是错的:)
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);
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.