Java jar文件中文件夹的路径
我有jar文件Java jar文件中文件夹的路径,java,jar,Java,Jar,我有jar文件langdetect.jar。 它的层次结构如图所示 在com/langdetect包中有一个类LanguageDetection。 在执行jar文件时,我需要从上面的类访问profiles.sm文件夹的路径 提前感谢。JAR只不过是Zip文件,Java提供了处理这些文件的支持 Java6(及更早版本) 您可以以ZipFile的形式打开jar文件,并对其条目进行迭代。每个条目在文件中都有一个完整的路径名,没有相对路径名。尽管您必须注意,所有条目(尽管在zip文件中是绝对的)都不要
langdetect.jar
。
它的层次结构如图所示
在com/langdetect
包中有一个类LanguageDetection
。
在执行jar文件时,我需要从上面的类访问profiles.sm
文件夹的路径
提前感谢。JAR只不过是Zip文件,Java提供了处理这些文件的支持 Java6(及更早版本) 您可以以
ZipFile
的形式打开jar文件,并对其条目进行迭代。每个条目在文件中都有一个完整的路径名,没有相对路径名。尽管您必须注意,所有条目(尽管在zip文件中是绝对的)都不要以“/”开头,如果需要,您必须添加它。下面的代码段将为您提供类文件的路径。className
必须以.class
结尾,即LanguageDetection.class
String getPath(String jar, String className) throws IOException {
final ZipFile zf = new ZipFile(jar);
try {
for (ZipEntry ze : Collections.list(zf.entries())) {
final String path = ze.getName();
if (path.endsWith(className)) {
final StringBuilder buf = new StringBuilder(path);
buf.delete(path.lastIndexOf('/'), path.length()); //removes the name of the class to get the path only
if (!path.startsWith("/")) { //you may omit this part if leading / is not required
buf.insert(0, '/');
}
return buf.toString();
}
}
} finally {
zf.close();
}
return null;
}
Java 7/8
您可以使用JAR文件的Java7文件系统支持打开JAR文件。这允许您像操作普通文件系统一样操作jar文件。因此,您可以遍历文件树,直到找到文件并从中获取路径。下面的示例使用Java8流和Lambdas,Java7的版本可以从中派生出来,但会稍微大一点
Path jarFile = ...;
Map<String, String> env = new HashMap<String, String>() {{
put("create", "false");
}};
try(FileSystem zipFs = newFileSystem(URI.create("jar:" + jarFileFile.toUri()), env)) {
Optional<Path> path = Files.walk(zipFs.getPath("/"))
.filter(p -> p.getFileName().toString().startsWith("LanguageDetection"))
.map(Path::getParent)
.findFirst();
path.ifPresent(System.out::println);
}
如果jar的根目录中只有一个profiles.sm
,只需
String basePath = "/profiles.sm/";
URL resource = LanguageDetection.class.getResource(basePath + "myResource.txt");
如果您在/profiles.sm
中有多个Jar和一个资源,那么您可以通过类加载器访问所有这些Jar,然后从类的URL中提取Jar文件
for(URL u : Collections.list(LanguageDetection.class.getClassLoader().getResources("/profiles.sm/yourResource"))){
System.out.println(u);
}
在任何情况下,如果不访问zip/jar文件就无法浏览此路径或文件夹的内容,因为Java不支持浏览classpath中包/文件夹内的类或资源。您可以使用lib来实现这一点,或者通过使用上面的zip示例额外读取检测到的jar的内容来扩展上面的ClassLoader示例。您看过这个示例吗?可能会有帮助;jar与否在这里是一样的,只要它在类路径中,我尝试使用DetectorFactory.loadProfile(LanguageDetection.class.getResource(“profiles.sm”).getPath());但是没有帮助Hi gerald,谢谢,但是我需要在jre1.6上运行我的jar文件。需要一些替代方法。
for(URL u : Collections.list(LanguageDetection.class.getClassLoader().getResources("/profiles.sm/yourResource"))){
System.out.println(u);
}