首页 > 解决方案 > 以编程方式创建 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 中?或者依赖项所在的路径在哪里,以便我可以包含它们?

标签: javajar

解决方案


推荐阅读