java - 如何仅将所选文件夹内的内容添加到 jar
问题描述
所以我有这个 java 程序,当我们给出内容的路径时,它会生成一个 jar 文件。但问题是它会在 jar 文件中生成更多目录。例如假设相关内容在目录中/home/user/Desktop/sample/bin/tmp
。当我创建 jar 文件时,它里面有所有这些目录,这意味着主目录里面有user
目录,里面有Desktop
目录等等,直到tmp
添加文件夹内的内容。但我想要的是,将此tmp
文件夹内的内容直接添加到 jar 中,而不添加那些额外的目录。这是我使用的代码,我想修改它或完全重写它。有什么想法吗...?
private static void createJar(File source, JarOutputStream target) throws IOException
{
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())
createJar(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();
}
finally
{
if (in != null)
in.close();
}
}
请注意,这source
是目录,而target
是我要创建的 jar 文件。
解决方案
我找到了答案。希望有人会像我一样需要它。
private static void createJar(File source, JarOutputStream target) {
createJar(source, source, target);
}
private static void createJar(File source, File baseDir, JarOutputStream target) {
BufferedInputStream in = null;
try {
if (!source.exists()){
throw new IOException("Source directory is empty");
}
if (source.isDirectory()) {
// For Jar entries, all path separates should be '/'(OS independent)
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()) {
createJar(nestedFile, baseDir, target);
}
return;
}
String entryName = baseDir.toPath().relativize(source.toPath()).toFile().getPath().replace("\\", "/");
JarEntry entry = new JarEntry(entryName);
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 (Exception ignored) {
} finally {
if (in != null) {
try {
in.close();
} catch (Exception ignored) {
throw new RuntimeException(ignored);
}
}
}
}
推荐阅读
- python - 自 lxml v4.4 以来,etree.iterwalk 不再遍历处理指令
- angular - Ionic 4 网格 - 每行仅显示一列
- swift - mapkit - 显示自定义图像
- r - 在 R 中满足条件时按组 AND 顺序排序
- php - 多维数组合并为单线数组
- javascript - 当工具提示反应时光标移动到输入的末尾
- swiftui - 如何在 SwiftUI 中制作内阴影?
- r - 当主 df 中的日期在小 df 的范围内时,R 总结
- database - 是否有任何解决方法可以在 Windows 上安装 Greenplum 数据库
- javascript - 如何在 Excel 单元格中插入换行符