1 回答
TA贡献1853条经验 获得超6个赞
因此,经过更多研究后,上述代码只能在 Windows 的 IDE 中运行,但对于 jar 文件则失败,因此我在 Linux 和 Windows 中得到的结果。
以下是我正在使用的工作解决方案。它可以以更简洁的方式重写,但由于时间原因,我保留了原样。它适用于类路径和 Jar 文件。
String directory = "/this/is/my/package/containing/data/";
请注意,包名称目录中需要开头斜杠。
String path = ClassLoader.class.getResource(directory).toExternalForm();
if (path.startsWith("jar")) {
try {
URL url = new URL(path);
System.out.println("JAR URL Name : " + url.toString());
JarURLConnection connection = (JarURLConnection) url.openConnection();
String jarFileName = connection.getJarFile().getName();
System.out.println("JAR File Name : " + jarFileName);
try (JarInputStream jarFile = new JarInputStream(new FileInputStream(jarFileName));) {
String regex = directory.substring(1);
do {
try {
JarEntry jarEntry = jarFile.getNextJarEntry();
if (jarEntry != null) {
String entryName = jarEntry.getName();
if (!regex.equals(entryName) && entryName.contains(regex)) {
System.out.println("JAR Entry Name : " + entryName);
try (InputStream in = YourClassName.class.getClassLoader().getResourceAsStream(entryName);
Scanner scanner = new Scanner(in);) {
//Do something in here
} catch (Exception ex) {
System.out.println(ex);
}
}
} else {
break;
}
} catch (IOException ex) {
System.out.println("JAR InputStream Error : " + jarFileName + " - > " + ex);
break;
}
} while (true);
}
} catch (Exception e) {
System.out.println("JAR URL Connection Error : " + e);
}
} else {
try {
URL url = new URL(path);
try (BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()))) {
String fileName;
while ((fileName = in.readLine()) != null) {
String filePath = directory + fileName;
try (InputStream is = ClassLoader.class.getResourceAsStream(filePath);
Scanner scanner = new Scanner(is);) {
//Do something here
} catch (Exception ex) {
System.out.println(ex);
}
}
}
} catch (Exception e) {
System.out.println("Classpath URL Connection Error : " + e);
}
}
}
添加回答
举报