[英]Java - Reading files inside jar
我知道有很多方法可以做到这一点,但是我在这个任务中遇到了一些问题,我无法用我已经找到的解决方案来解决。
首先,我不想读取 jar 中的特定文件:我想读取给定目录路径的 jar内目录中包含的所有文件。 也就是说,通过一些研究,我发现了如何做到这一点,并编写了一个测试代码。
public class StringLocalizer {
private final List<URL> files;
public StringLocalizer(final String stringsDirectory) throws URISyntaxException, IOException {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
final BufferedReader br = new BufferedReader(new InputStreamReader(loader.getResourceAsStream(stringsDirectory), StandardCharsets.UTF_8));
files = br.lines()
.map(l -> stringsDirectory + "/" + l)
.map(loader::getResource)
.collect(Collectors.toList());
// This line has the debug purpose of showing all the url contained in the list
System.out.println(Arrays.toString(files.toArray(new URL[files.size()])));
}
public static void main(String[] args) {
try {
new StringLocalizer("test/testDirectory/");
} catch (URISyntaxException | IOException e) {
e.printStackTrace();
}
}
}
首先,我在我的 IDE (Eclipse) 中尝试了代码,我得到了这个输出:
[file:/C:/Users/*my_user_name*/neon/workspace/JavaStringLocalizer/bin/test/testDirectory//test.xml]
代码运行良好,这是我的第一个想法,但是当我尝试将程序打包到一个可运行的 JAR 文件中时,我得到了一个意外的输出:
[]
为什么即使文件打包在JAR文件中,列表也是空的?
(正确的输出应该是包含给定目录中所有文件的数组的表示,如第一个输出)
编辑:为了更好地了解我的情况,我有以下文件:
>MyJar.jar
>classFiles
>test>testDirectory>test.xml // I want to get this file
注意:此目录将包含更多文件,因此我不想静态访问它们,但我想动态读取所有文件
编辑:使用ZipFile
提取文件的代码:
public class StringLocalizer {
private final List<ZipEntry> files = new ArrayList<ZipEntry>();
public StringLocalizer(final String stringsDirectory) throws URISyntaxException, IOException {
URL jarUrl = getClass().getProtectionDomain().getCodeSource().getLocation();
File jarFile = new File(jarUrl.toURI().getPath());
ZipFile unzipper = new ZipFile(jarFile, ZipFile.OPEN_READ);
ZipEntry dirEntry = unzipper.getEntry(stringsDirectory);
Enumeration<? extends ZipEntry> entries = unzipper.entries();
for(ZipEntry entry = entries.nextElement(); entries.hasMoreElements(); entry = entries.nextElement()) {
if(entry.getName().startsWith(dirEntry.getName()) && !entry.getName().equals(dirEntry.getName())) {
files.add(entry);
}
System.out.println(entry.getName());
}
System.out.println(Arrays.toString(files.toArray(new ZipEntry[files.size()])));
unzipper.close();
}
public static void main(String[] args) {
try {
new StringLocalizer("test/testDirectory/");
} catch (URISyntaxException | IOException e) {
e.printStackTrace();
}
}
}
为什么最后一个条目被忽略?
JAR 文件实际上是 ZIP 文件,因此只需将文件视为 ZIP,就像@Jamie建议的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.