what is the way to get get path dynamically as I am getting Getting java.io.FilenotFoundException while using FileStream

satmisha
satmisha used Ask the Experts™
on
Hi Experts,

I am trying to read text file which works great on my local but when I deploy it on server it creates problem because the path on server is different as that of my local.

My Local Path:
   C:\Folder1\Project\File.txt
Server Path:
 C:\F1\F2\F3\F4\Project\File.txt

So in code I have used like this:
 Java.IO.FileINputStream.open +  new FileInputStream("./Project/File.txt")

It works great on my local but fails when I deploy it on server, reason is path.

Is there any way I could make it dynamic so that it could itself detect the right path ?

Looking forward to hearing from you.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
IT Business Systems Analyst / Software Developer
Top Expert 2015
Commented:
Is "File.txt" a file that should be editable AFTER the code is compiled? ie. does it hold settings that need to be tweaked for deployment. Or once the application is compiled it will never change?

If the first statement applies, that it needs to change then what you are doing is acceptable solution, you just need to set the current working directory correctly when you execute your application on the server. If you are in the C:\F1\F2\F3\F4 directory when running it, it should work just fine. How you set this current directory is dependent on how/what/where you are running your app, you will need to give us more info on that if you need more help. There is really no other way for it to "detect" the right path.

However, if your file should be static once the app is compiled, then the most appropriate solution would be to include the File.txt in your source files, then they will be included on the classpath when you compile. In that case, put your File.txt file in the same folder as the .java file of the class that is reading it and then you can get an InputStream for the file, by doing this...

InputStream is = getClass().getResourceAsStream("File.txt");

By leaving referring to a relative path like above, it will look in the classpath in the same location that your class file for the class that is reading it is. Then this method will also work even if you create a .jar archive of your code.
You could also use a system property for the path and specify it on the command line
java -Dmypath=C:\Folder1\Project\ MyProgram

Or pass in the path as an argument to your program.
java MyProgram C:\Folder1\Project\ MyProgram

Author

Commented:
Apologies for late response. Thanks a lot for your help.
mccarlIT Business Systems Analyst / Software Developer
Top Expert 2015

Commented:
You're welcome!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial