[英]Not able to read file using relative path
I don't know what is wrong but I am getting noSuchFileException.The path is right I am able to access it though cmd. 我不知道出什么问题了,但是我收到了noSuchFileException.path是正确的,我可以通过cmd访问它。
Path file = Paths.get("../resources/input.txt");
BufferedReader reader = Files.newBufferedReader(file, Charset.defaultCharset());
Judging by the filename, you're trying to read a resource. 从文件名来看,您正在尝试读取资源。 A resource is not a file.
资源不是文件。 It is, conceptually at least, packaged inside a JAR or WAR or EAR file.
至少从概念上讲,它包装在JAR或WAR或EAR文件中。 You should use
Class.getResource()
and friends. 您应该使用
Class.getResource()
和朋友。 In this case probably getResourceAsStream()
is what you need, without the ..
. 在这种情况下,可能需要
getResourceAsStream()
,而没有..
Just to formalize it: 只是为了使其正式化:
Imagine a directory structure of: /foo/bar/example/test/file.txt
想象一下一个目录结构:
/foo/bar/example/test/file.txt
And a working directory of /foo/bar/example/
还有一个工作目录
/foo/bar/example/
And a username of bob
还有
bob
的用户名
. 。 (dot) - Refers to the current working directory (eg
/foo/bar/example/
in this case). (点) -指向当前工作目录(在这种情况下,例如
/foo/bar/example/
)。
.. (dot dot) - Refers to the parent directory (eg /foo/bar/
in this case). ..(点点) -指向父目录(例如,在这种情况下为
/foo/bar/
)。
~ (tilde) [Unix-like only/shell only] - Refers to the user's home directory (eg /home/bob/
) 〜(波浪号) [仅限于类Unix /仅用于shell]-引用用户的主目录(例如
/home/bob/
)
Directly starting a directory name without the preceding slash (eg test/file.txt
) is equivalent to using the single dot (ie paths are resolved relative to the current working directory). 不以斜杠直接启动目录名称(例如
test/file.txt
) 等效于使用单点(即,相对于当前工作目录解析路径)。
Directly starting a directory name with the preceding slash (eg /test/file.txt
) and you are now specifying an absolute path (on Unix) from root (or, in the case of Windows, from the drive the working directory resides in). 直接以前面的斜杠开头的目录名称(例如
/test/file.txt
),现在您从根目录(或在Windows的情况下,从工作目录所在的驱动器)指定绝对路径(在Unix上) 。
A special case exists where . 存在一个特殊情况。 (dot) and .. (dot dot) refer to the same directory, if and only if the current working directory is at root
/
("absolute" root or a chroot jail, either way). (且) 仅在当前工作目录位于根目录
/
(“绝对”根目录或chroot监狱,无论哪种情况)时,(点)和..(点点)引用相同的目录。 The equivalent in windows is at a drive root (eg C:\\
). Windows中的等效项位于驱动器根目录(例如
C:\\
)。
也许您可以尝试通过file.toAbsolutePath().normalize()
检查BufferedReader所采用的路径,以查看没有冗余元素的结果路径
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.