Reading files from a directory by giving relative paths
Joined: Aug 25, 2005
I want to read a file from a directory which is in parallel to the current directory.
For example, consider the following directory structure: -
In Tester.java i want to read the text.txt file which is actually in a directory parallel to the enclosing directory of Tester class.
I am trying to access the file by giving the path argument to the File class as
... but i get FileNotFoundException ... shouldn't the string argument that i provided go one level up( since i have specified two dots as we do while accessing directory in Linux) and then into the resources directory to access the test.txt ?
I want to access the the test.txt relative to the Tester.java ... because i can give the entire src folder to my friend ... he can put in any directory and try to run it without any change to the code!
How do i access the file relatively ? ... is my way of accessing the file relatively incorrect ?
P.S. By the way i am using Windows Vista Home Basic Edition OS and Java 1.6
Thanks and regards
Thanks and Regards
Omkar Patkar (SCJP 1.4)[url]http://javacollectionsnotes.blogspot.com[/url] | [url]http://omkar-myscjpexp.blogspot.com[/url]
The current folder (which the .. uses) is not Project\src\org\omkar\tester as you think, but the path where you were when you started the JVM. It's most likely Project\src, but you can always find out by printing the return value of System.getProperty("user.dir").
I tried accessing the file by using the getResourceAsStream() API ... and it worked!
I had to specify the file as if it was only another java file with its package structure (... "dot" replaced with "forward slash")
I mean i accessed the file as "/org/omkar/resources/test.txt" ... now since my package structure is not going to change ... even if i give this to my friend,
the code should run on his machine as well!
Thanks a lot ! ... but i was wondering .... if the way by which i was trying earlier to give relative position of the file by using the syntax of double dots ".." and the file separator is right? .... does JVM understand this syntax that "..\" means go one level up of current directory ? .. or this syntax is understood only by Linux based OS ?