javafilenullpointerexceptionnosuchfileexception

Java isn't getting the file in the source code when compiled


Recently I have an issue with Java. I've tried some things I found on the web but they haven't worked, so I need help. I have a Java project in Eclipse. My main class is in src/programCode/UI_Main2.java. In that .java I try to access to a file in src/files/File.file

And this is when the things fo weird.

So, I don't know what to do. src/files/File.file is the only one that works, but it doesn't when compiled to executable jar. So please, help me, I haven't found any solution yet. Thanks!


Solution

  • Finding a file depends on two things:

    Under Unix-like system when you use path like /dir1/dir2/file you use absolute path, so your working directory doesn't matter, but you must have a file exactly under that path.

    In your case you try to use relative path, so you shouldn't use / at the beginning.

    This case is crucial to your problem:

    "If I use src/files/File.file it works in Eclipse but when I compile it to a executable .jar it gives me NoSuchFileException." 
    

    By default Eclipse uses as working directory a parent directory of src (which is usually a direcotry with your project", so starting from there you indeed have a file under that path.

    When you start a .jar your working directory is somewhere else. Put your .jar to parent directory of src and it should work.

    Now, I suggest that you change location of the file to a directory other than src (call it Resurces or something) and provide it along with the .jar.

    Also, here is an interesting discussion about working directories and .jar files:

    Current working directory when running a Jar

    If you want to distribute a single .jar here is a good packaging instruction:

    http://www.cefns.nau.edu/~edo/Classes/CS477_WWW/Docs/pack_resources_in_jar.html