Search code examples
javafileloadinggetresource

Loading a file (externally)


Got a little problem loading a file! (Not a image just really a file like .txt and stuff) It loads fine in Netbeans with

    File myfile = new File("a/b/myfile.abc");

The problem is the compiled jar gets a exception and doesn't find the file. I need it as a file, not as a Stream or something, that's the problem and I have already tried everything that came into my mind to load it. I would like to load it externally (not from inside the jar) and the problem is it doesn't seem possible to get a working setup with getRessource(AsStream).

EDIT: Ok so i let it print the absolute path when it was compiled and when it was not compiled. Non compiled path:

C:\Users\USERNAME\Documents\NetBeansProjects\ProjectName\a\b\myfile.abc <-- Correct Path

Compiled path:

C:\Users\USERNAME\a\b\myfile.abc <-- Not Correct Path

Can anybody tell me how to fix this? EDIT²: If I navigate to the correct folder with cmd (cd etc.) and start the jar after doing so the folder is getting loaded from the correct directory. Can someone tell me what I need to change? EDIT³: When not starting with cmd it seems to search for the folder in Windows/system32 :O


Solution

  • When you construct a file with

    new File("abc.txt")
    

    the abc.txt file is supposed to be in the current directory. The current directory is the directory from which the java command is launched to execute your application. So, if you're in c:\foo\bar and execute java -cp d:\java\app\MyApplication.jar MyApplication, it will look for the file c:\foo\bar.

    The location of the jar of the application is irrelevant, and doesn't have any impat on where the file is looked up. The current directory is what matters.