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.
If I use
/src/files/File.file
it gives meNoSuchFileException
.If I use
src/files/File.file
it works in Eclipse but when I compile it to a executable .jar it gives meNoSuchFileException
.If I use
/files/File.file
it gives meNoSuchFileException
.If I use
files/File.file
it gives meNoSuchFileException
.If I use
files/File.file
it gives meNoSuchFileException
.If I use
this.getClass().getResource("/files/File.file").getPath().substring(1)
(without substring it gives me Invalid character) it gives meNoSuchFileException
(but it shows me the absolute path and the file exists there!)If I use
this.getClass().getResource("files/File.file").getPath()
it gives meNullPointerException
and the program crashes.If I use
this.getClass().getResource("src/files/File.file").getPath()
it gives meNullPointerException
and the program crashes.If I use
this.getClass().getResource("/src/files/File.file").getPath()
it gives meNullPointerException
and the program crashes.
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!
Assuming your intent is to rum your compiled program on YOUR own development computer, you need to provide the full path to the file you want. That full path would be of the form
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:
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 ofsrc
and it should work.Now, I suggest that you change location of the file to a directory other than
src
(call itResurces
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