简体   繁体   English

Java-使用getResourceAsStream(String)读取资源

[英]Java - Read resource with getResourceAsStream(String)

Can someone explain why Java does not find resource if using File.separator in the String for search path in getResourceAsStream(String name) ? 有人可以解释为什么如果在String File.separator用于getResourceAsStream(String name)搜索路径,为什么Java找不到资源? I have this code: 我有以下代码:

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
}

I have found out, that File.separator used Backslashes instead of Slashes. 我发现, File.separator使用反斜杠而不是斜杠。 But I hoped that File.separator is more flexible. 但我希望File.separator更灵活。 In this case, it isnt. 在这种情况下,它不是。 And I want to know, why. 我想知道为什么。 Thanks alot. 非常感谢。

Because when you pass \\\\ separator to getResourceAsStream() method it interprets path to your dir in another way, added package name before dir actually. 因为当您将\\\\分隔符传递给getResourceAsStream()方法时,它将以另一种方式解释目录的路径,因此实际上在目录之前添加了程序包名称。

Class javadoc 类javadoc

Before delegation, an absolute resource name is constructed from the given resource name using this algorithm: 在委派之前,使用以下算法从给定资源名称构造绝对资源名称:

 If the name begins with a '/' ('\/'), 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 '.' ('\.'). 

Your File.separator returns different result for unix and windows machines. 您的File.separator对于UNIX和Windows计算机返回不同的结果。 If you use mack or unix in this case your code will works but in win machine fails. 如果在这种情况下使用mack或unix,则您的代码将可用,但在win机器中将失败。

File javadoc 文件javadoc

public static final char separatorChar 公共静态最终字符分隔符

The system-dependent default name-separator character. 取决于系统的默认名称分隔符。 This field is initialized to contain the first character of the value of the system property file.separator. 初始化此字段以包含系统属性file.separator值的第一个字符。 On UNIX systems the value of this field is '/'; 在UNIX系统上,此字段的值为'/'; on Microsoft Windows systems it is '\\'. 在Microsoft Windows系统上,它是'\\'。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM