【问题标题】:Java - Read resource with getResourceAsStream(String)Java - 使用 getResourceAsStream(String) 读取资源
【发布时间】:2017-12-08 00:23:06
【问题描述】:

如果在getResourceAsStream(String name) 中的搜索路径字符串中使用File.separator,有人可以解释为什么Java 找不到资源吗?我有这个代码:

private final String RESOURCE_PATH = File.separator + "dir" + File.separator;
private final String SAME_PATH_HARDCODED = "/dir/";

public void findResource(String fileName) {
    InputStream file1 = ThisClass.class
            .getResourceAsStream(RESOURCE_PATH + fileName);  // returns null

    InputStream file2 = ThisClass.class
            .getResourceAsStream(SAME_PATH_HARDCODED + fileName);  // returns file
}

我发现File.separator 使用了反斜杠而不是斜杠。但我希望 File.separator 更灵活。在这种情况下,它不是。我想知道,为什么。非常感谢。

【问题讨论】:

  • 我也试过了,但没有任何异常。
  • 没有异常,因为这个方法找不到返回null。

标签: java resources


【解决方案1】:

因为当您将\\ 分隔符传递给getResourceAsStream() 方法时,它会以另一种方式解释您的目录的路径,实际上在目录之前添加了包名称。

Class javadoc

在委托之前,绝对资源名称由 使用此算法给定资源名称:

If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:

    modified_package_name/name 

Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').

您的File.separator 为 unix 和 windows 机器返回不同的结果。如果您在这种情况下使用 mack 或 unix,您的代码将可以工作,但在 win 机器中会失败。

File javadoc

公共静态最终字符分隔符

系统相关的默认名称分隔符。这个字段是 初始化为包含系统值的第一个字符 属性文件.分隔符。在 UNIX 系统上,该字段的值为 '/';在 Microsoft Windows 系统上,它是 '\'。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 2013-04-25
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    相关资源
    最近更新 更多