Issue
I'm currently working on a Java project in which I have to open files I stored in a data directory next to src.
When I launch my program from Eclipse, to access these files: I type "data/fileName"
whereas when I use console I have to type "../data/fileName"
.
(I couldn't manage to execute java src/Main
from project directory and got the error :
Error: Could not find or load main class src.Main.java
Caused by: java.lang.ClassNotFoundException: src.Main.java
)
Is there a way to make my program runnable on both console and Eclipse?
To give some context: I usually intended to run only on Eclipse but I encountered issues launching nano from Eclipse ($TERM variable , redirecting pipes to dev/tty also) so console execution has become a requirement.
I can't change my Eclipse configuration since this project won't be run on my computer and if it doesn't run because of default Eclipse settings, well...
Thank you for your replies.
Cordially.
Solution
Yes. Don't put those files there. There are 2 broad categories:
- Read-only data that is as much a part of your app as your class files are. Think 'list of US states for the 'state' dropdown', 'an icon png to be shown on my user interface', 'a file containing a bunch of SQL to be used to initialize an empty database', and more.
For this, the proper way to go is YourClass.class.getResourceAsStream("foo.txt")
, which will give you an input stream for reading the file "foo.txt", which is in the same place "YourClass.class" is. Even if it is in a jar file, for example.
This does mean that as part of your build, these files need to be in the jar. eclipse's limited build system does this. If you level up as a programmer and use a build system (you should be levelling up here), put them in src/main/resources and the build system should take care of it.
- Or, the second category: Files that the user is supposed to edit, or files that need to be modified by your app.
These don't go anywhere near your jar file; executable and user-editable stuff should be nowhere near each other. These should be in the user home dir, you can fetch it with System.getProperty("user.home")
.
Note that to run java stuff, 'src' shouldn't be part of the story at all, java
can't run source files, only class files. Also, the argument isn't a dir, it's a class name. java -cp path/to/your/app.jar com.foo.pkg.YourClass
is how you run java code, not java src/Main
.
Answered By - rzwitserloot