Here you can find the source of createJarFile(Path directory, String name, Optional
private static Path createJarFile(Path directory, String name, Optional<Manifest> manifest, Class[] classesToAdd, Map<String, Path> filesToAdd) throws Exception
//package com.java2s; //License from project: Apache License import java.io.InputStream; import java.io.OutputStream; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Map; import java.util.Optional; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; public class Main { private static final String CLASS_EXTENSION = ".class"; private static final String FILE_SEPARATOR = FileSystems.getDefault().getSeparator(); private static Path createJarFile(Path directory, String name, Optional<Manifest> manifest, Class[] classesToAdd, Map<String, Path> filesToAdd) throws Exception { Path outputFile = directory.resolve(name); OutputStream fileOutputStream = Files.newOutputStream(outputFile); try (JarOutputStream outputStream = manifest.isPresent() ? new JarOutputStream(fileOutputStream, manifest.get()) : new JarOutputStream(fileOutputStream, new Manifest())) { for (Class currentClass : classesToAdd) { addClass(outputStream, currentClass); }/*from w w w .j av a 2s. c o m*/ for (String entryName : filesToAdd.keySet()) { Path file = filesToAdd.get(entryName); addPath(outputStream, file, entryName); } } return outputFile; } private static void addClass(JarOutputStream outputStream, Class currentClass) throws Exception { String resourceName = classToResourceName(currentClass); Path classFile = classToPath(currentClass); addPath(outputStream, classFile, resourceName); } private static void addPath(JarOutputStream outputStream, Path path, String entryName) throws Exception { outputStream.putNextEntry(new JarEntry(entryName)); if (!Files.isDirectory(path)) { try (InputStream inputStream = Files.newInputStream(path)) { while (inputStream.available() > 0) { outputStream.write(inputStream.read()); } } } outputStream.closeEntry(); } public static String classToResourceName(Class currentClass) throws Exception { return currentClass.getCanonicalName().replace(".", FILE_SEPARATOR) + CLASS_EXTENSION; } public static Path classToPath(Class currentClass) throws Exception { return Paths.get(currentClass.getResource(FILE_SEPARATOR + classToResourceName(currentClass)).toURI()); } }