Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Relative Path Problem  RSS feed

 
Gaurav Chikara
Ranch Hand
Posts: 413
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have made a file say "hello.txt" in the same directory as in which i m creating my class file
This is the following code snippet
package test;
import java.io.*;
public class FileTest {
public static void main(String g[])
{
new FileTest().Testme();
}
public void Testme(){
String file= "/hello.txt";
try
{
FileInputStream fin = new FileInputStream(file);
System.out.println("File found");
}
catch(FileNotFoundException e){System.out.println("File Not Found");
}
}
}
But I am getting the FileNotFound Exception
It finds this file only in the case where I put hello.txt in the root drive(say c drive)
Can anyone pls let me know as how can i give the relative path
I need this relative path for the experimental web server which i m trying to make so that
request comes from the home directory of the web server
 
David Weitzman
Ranch Hand
Posts: 1365
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The most reliable way would be to have some method somewhere (Configuration.getBaseDirectory() or something) that returns whatever directory you're interested in. Sometimes people have launching scripts pass a working diretory option to the JRE (i.e. "java -Dmyapp.home=/some/directory pak.MainClass") so they can just call System.getPropery("myapp.home") from anywhere.
Another option is assume that your program is being lauched from a specific directory (the working directory) and just make all paths relative to that. If there's a launch script the user is expected to use in the projhome/bin directory, the file "../work" is the same as "projhome/work". That's the lazy way -- I do it all the time .
[ September 21, 2002: Message edited by: David Weitzman ]
 
Rodney Woodruff
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could also call System.getProperty("user.dir"). This will give you the current working directory. So for example:


[ September 25, 2002: Message edited by: Rodney Woodruff ]
 
Rene Larsen
Ranch Hand
Posts: 1179
Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you put the txt-file in the same folder as the class-file, then you should call it like this:

You have to remember that the program is looking in the root of the package-path, so you need to add the package to the file.
Rene
[ September 25, 2002: Message edited by: Rene Larsen ]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!