Java - 从jar获取文件



我需要在应用程序中捕获一些目录。为此,我有一个小演示:

String pkgName = TestClass.class.getPackage().getName();
String relPath = pkgName.replace(".", "/");
URL resource = ClassLoader.getSystemClassLoader().getResource(relPath);
File file = new File(resource.getPath());
System.out.println("Dir exists:" + file.exists());

从 IDE 运行应用程序时,我收到了我的目标,我可以找到我的目录。但是将应用程序作为 JAR 文件运行,不会返回有效的"文件"(从 Java 的角度来看(,我的 sout 给了我File exists:false。有没有办法获取这个文件?在这种情况下,文件是一个目录。

Java ClassPath是一个不同于文件系统抽象的抽象。类路径元素可能以两种物理方式存在:

  1. 类路径指向根目录时分解
  2. 打包在 JAR 存档中

不幸的是,如果类路径指向文件系统,则 file.getPath 确实返回一个 File 对象,但如果引用 JAR 文件,则不会返回。

在 99% 的情况下,您应该使用 InputStream 读取资源的内容。

这是一个片段,它使用来自apache commons-io的IOUtils将整个文件内容加载到字符串中。

public static String readResource(final String classpathResource) {
    try {
        final InputStream is = TestClass.class.getResourceAsStream(classpathResource);
        // TODO verify is != null
        final String content = IOUtils.toString(
            is, StandardCharsets.UTF_8);
        return content;
    } catch (final IOException e) {
        throw new UncheckedIOException(e);
    }
}

最新更新