I am using netbeans; I can't figure out the way we are supposed to structure the project when we want to access a ressource file (e.g. a txt file that contains static info):
Here is a simple example, I have a file called Test.java that reads inside a txt file called myfile.txt
I want to type something like :
public class Test {
public static void main(String[] args) {
try{
File f = new File("myfile.txt");
Scanner s = new Scanner(f);
System.out.println(s.next());
}
catch(Exception e){
e.printStackTrace();
}
}
}
which seems reasonnable if the myfile.txt is located in the same directory as the .java file.
But NO it seems that if I type my code like that, the txt file should be at the same level as src/ that is the root of my project. Ok I'll accept that and put the txt there, so I clean and build. Now if I run in netbeans (the green arrow button) it runs fine (even if there is no txt file in my build folder, which seems strange) BUT of course if I try to execute directly the jar in the dist folder (which should be the thing you want to distribute once the project is finished) the program fails since there is no txt folder inside the jar ofr next to it.
Ok so I change my strategy and go for the thing which seemed logical, that is put my txt inside the src directory. When I build it appears in the build directory, and also inside the jar.
BUT the program fails (both within netbeans and outside) since the path to the file is not proper in the new File command. So I could change and type
public class Test {
public static void main(String[] args) {
try{
File f = new File("src/myfile.txt");
Scanner s = new Scanner(f);
System.out.println(s.next());
}
catch(Exception e){
e.printStackTrace();
}
}
}
but now of course it won't run outside netbeans because the src folder does not mean anything to the poor .jar file.
I can't find a way to address this supposedly trivial task.
Can you help me?