Shruti Rawat
Shruti Rawat

Reputation: 697

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.

Path file = Paths.get("../resources/input.txt");
            BufferedReader reader = Files.newBufferedReader(file, Charset.defaultCharset());    

Upvotes: 0

Views: 1434

Answers (3)

initramfs
initramfs

Reputation: 8415

Just to formalize it:

Imagine a directory structure of: /foo/bar/example/test/file.txt

And a working directory of /foo/bar/example/

And a username of bob


. (dot) - Refers to the current working directory (e.g. /foo/bar/example/ in this case).

.. (dot dot) - Refers to the parent directory (e.g. /foo/bar/ in this case).

~ (tilde) [Unix-like only/shell only] - Refers to the user's home directory (e.g. /home/bob/)

Directly starting a directory name without the preceding slash (e.g. test/file.txt) is equivalent to using the single dot (i.e. paths are resolved relative to the current working directory).

Directly starting a directory name with the preceding slash (e.g. /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).


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). The equivalent in windows is at a drive root (e.g. C:\).

Upvotes: 0

hetec
hetec

Reputation: 359

Maybe you can try to check the path taken by the BufferedReader through file.toAbsolutePath().normalize() to see the resulting path without redundant elements

Upvotes: 0

user207421
user207421

Reputation: 311029

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. You should use Class.getResource() and friends. In this case probably getResourceAsStream() is what you need, without the ...

Upvotes: 2

Related Questions