【问题标题】:How to get absolute directory path from relative path + classloader如何从相对路径+类加载器获取绝对目录路径
【发布时间】:2017-02-01 10:07:06
【问题描述】:

我有一个类,它的构造函数接收一个相对资源路径(语言属性文件)和对应的类加载器(路径是相对于类加载器的包):

public Language(String relDir, ClassLoader classLoader) {
    ...
}

在那个类中,我有一个方法可以加载所有找到的资源文件(属性文件,如 MyFile_en_GB.properties),它事先不知道会有多少语言资源。它使用 languagesDir 作为查找资源的绝对路径。

private void loadLanguages() {
    DirectoryStream.Filter<Path> filter = (path) -> {
      return Files.isRegularFile(path) & path.getFileName()toString().startsWith("MyFile");
    };
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(languagesDir, filter)) {
        for (Path entry : stream) {
          String fileName = entry.getFilename().toString();
          ...
          loadPropertiesFile(filename)
        }
    } catch (..) {}
}

在那里,languagesDir 使用绝对路径。但是,当我尝试时:

String dir = classLoader.getResource(relDir).toString();

它抛出一个异常。我猜这是因为它需要一个文件而不是目录

如何获取资源的绝对路径?我应该尝试另一种方法并仅使用相对路径(如何做到这一点)?

编辑:关于异常: classLoader.getResource(relDir) 给出了一个空 URL

【问题讨论】:

  • it throws an exception. 请编辑您的帖子并添加例外。
  • 类加载器的资源不一定是文件。它们可能是 jar 条目。您不应该尝试使用文件系统操作来操作资源。

标签: java classloader relative-path resourcebundle absolute-path


【解决方案1】:

在将 URL 更改为文件后尝试使用 resourceFile.getName()。

URL resourceURL = classLoader.getResource(..);
File resourceFile = new File(new URL(resourceURL).toURI());
String fullPath = resourceFile.getName();

【讨论】:

  • 我从第一条指令中得到一个空 URL
  • 当然 - 你必须使用你的资源 - 在你的例子中 dirPath + "\\" + fileName
【解决方案2】:

它抛出一个异常。我想这是因为它需要一个文件并且 不是目录

如果是这种情况,您可以提供文件而不是目录。要获取绝对路径,请尝试如下

       String dirPath = "C:\\Softwares";

        File dir = new File( dirPath );

        for ( String fileName : dir.list() ) {

            File file = new File( dirPath + "\\" + fileName );

            if ( file.isFile() ) {

                // System.out.println( file.getAbsolutePath() );
                String dir = classLoader.getResource( file.getAbsolutePath() ).toString();
            }
        }

【讨论】:

    猜你喜欢
    • 2010-09-21
    • 1970-01-01
    • 2022-06-10
    • 2011-08-11
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多