简体   繁体   English

路径不起作用; 使用File.separator

[英]Path not working; using File.separator

I'm using: 我正在使用:

  • jdk 1.8.0.71 杰克1.8.0.71
  • IntelliJ 2016.3.2 IntelliJ 2016.3.2
  • Win7 Win7的

I was curious why this path is not working: 我很好奇为什么这条路不起作用:

public static final String ZPL_TEMPLATE =
                    File.separator
                    + "templates"
                    + File.separator
                    + "Template.txt";

yet this one works fine: 但是这个很好用:

public static final String TEMPLATE = "/templates/Template.txt";

Here is where is used (this is in another package): 这是使用位置(在另一个软件包中):

InputStream is = this.getClass().getResourceAsStream(TEMPLATE);

EDIT: the exception: 编辑:例外:

...
java.lang.NullPointerException: null
    at java.io.Reader.<init>(Reader.java:78)
    at java.io.InputStreamReader.<init>(InputStreamReader.java:72)
    ...

Becaseuse file separator on Win 7 is '\\' and as it states in doc for getResourceAsStream Becaseuse在Win 7上的文件分隔符为'\\',如文档中针对getResourceAsStream所述

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 '/'. 如果名称以'/'('\\ u002f')开头,则资源的绝对名称是名称中'/'之后的部分。 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 '.' 否则,绝对名称的格式如下:modified_pa​​ckage_name / name,其中Modifyed_pa​​ckage_name是此对象的程序包名称,用“ /”代替“。”。 ('\.'). ('\\ u002e')。

When accessing a internal resource, like you did with getResouceAsStream , the file separator must be / . 当访问内部资源时,就像使用getResouceAsStream ,文件分隔符必须为/

I believe that you are in a Windows machine, so the file separator is \\ . 我相信您在Windows计算机中,因此文件分隔符为\\

For more information, see How to use file separator when loading resources . 有关更多信息,请参见加载资源时如何使用文件分隔符

getResourceAsStream expect a resource name as a parameter, not a file path. getResourceAsStream期望将资源名称作为参数,而不是文件路径。

Resources names in java are separated by forward slashes / , no matter the file system (Resources names/path represents a path on the classpath, not on the filesystem). 无论文件系统如何,java中的资源名称都用正斜杠/分隔(资源名称/路径表示类路径上的路径,而不是文件系统上的路径)。

Hence, you can't use the file system seperator to build the resource name. 因此,您不能使用文件系统分隔符来构建资源名称。 On windows, it will be a backslash \\ 在Windows上,它将是反斜杠\\

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

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