java - 以编程方式创建 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 中?或者依赖项所在的路径在哪里,以便我可以包含它们?
解决方案
推荐阅读
- ios - 当我开始使用 WKWebViewOnly 时,Auth0 登录停止工作
- angular - 如果我使用 compareWith,如何从 ngSelected 获取选定值?
- javascript - 提取特定 ID 的 Google 脚本
- r - Crowly 的第 2.8.6 章 R 书
- azure - 通过 cmdlet 或 rest api 在 Azure 合作伙伴中心注册 Azure 应用
- kotlin - Kotlin/Native compileKotlinIosX64 任务在构建 iOS 应用程序时失败
- visual-studio-code - 强制 VS Code 安装扩展而不进行兼容性检查
- sql - 聚集索引中的最佳列顺序
- android-studio - 如何在 Android Studio 上修复应用程序模拟器
- python - 带有 GPU 的 Google Colab 上的 Cupy 内存错误 - 但只是我第二次运行代码