以编程方式创建胖子

时间:2019-09-16 19:23:04

标签: java jar

我正在尝试以编程方式创建 fat-jar 。到目前为止,我设法用我的代码创建了一个Jar文件。问题是,如果运行此命令,则会收到一个异常,提示Cannot load user class: org.company.bla.bla

这是我的代码

    private static void createJar() throws IOException {

        Manifest manifest = new Manifest();
        manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
        JarOutputStream target = new JarOutputStream(new FileOutputStream("events.jar"), manifest);

        Path root = Paths.get(".").normalize().toAbsolutePath();
        System.out.println(root.toString());

        Files.walk(root).forEach(f -> add(f.toFile(), target));

        target.close();
    }

    private static void add(File source, JarOutputStream target)
    {
        BufferedInputStream in = null;
        try {
            if (source.isDirectory()) {
                String name = source.getPath().replace("\\", "/");
                if (!name.isEmpty()) {
                    if (!name.endsWith("/"))
                        name += "/";
                    JarEntry entry = new JarEntry(name);
                    entry.setTime(source.lastModified());
                    target.putNextEntry(entry);
                    target.closeEntry();
                }
                for (File nestedFile: source.listFiles())
                    add(nestedFile, target);
                return;
            }

            JarEntry entry = new JarEntry(source.getPath().replace("\\", "/"));
            entry.setTime(source.lastModified());
            target.putNextEntry(entry);
            in = new BufferedInputStream(new FileInputStream(source));

            byte[] buffer = new byte[1024];
            while (true) {
                int count = in.read(buffer);
                if (count == -1)
                    break;
                target.write(buffer, 0, count);
            }
            target.closeEntry();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

如何将依赖项添加到此Jar中?还是依赖项所在的路径在哪里,以便我可以包含它们?

0 个答案:

没有答案