Quick disclaimer: I am very new to java and I know that this question has been answered in other threads, but I can't understand the answers there so I'm really hoping for a very simple/understandable explanation please.
Anyway, my problem is that I am using Eclipse to make a program which uses text files and pictures and while it works through Eclipse, if I try to export it into a runnable jar, I cannot access my resources anymore. Currently my directory structure when I run things from Eclipse is:
Desktop -->
workspace -->
QuizProgram -->
bin
src
Questions.txt
right.png
and I access my image and text files through:
BufferedReader br = new BufferedReader(new FileReader("Questions.txt"));
BufferedImage right = ImageIO.read(new File("Right.png"));
If anyone could please I give me a step-by-step explanation of where to move my files/change my code I would appreciate it very much. I've looked through many other threads and Classpath/ClassLoader are really confusing me. I've tried some
this.getClass().getResource("File.txt");
stuff also but nothing seems to work. Please help, I have a finished program and this last thing is really frustrating, thanks!
Edit 1: So I tried what user2933977 suggested and changed getResource to getResourceAsStream and everything worked wonderfully! Thanks a lot user2933977 for your help.
Side note: Yeah, yeah I get that this is a duplicate but I think that how you phrase a question and interact with responders helps a lot anyway. Take it easy, I got it to work.
You're not quite showing enough code but to use getResource(), your file would need to live in the same directory as where your .class files live. For example, you may have something that looks like:
Desktop -->
workspace -->
QuizProgram -->
bin -->
QuizProgram -->
YourClass.class
src -->
QuizProgram -->
YourClass.java
Questions.txt
right.png
I'm guessing a bit here but that is the default "Java Project" in Eclipse. So move your Questions.txt to the same directory as your .java file and Eclipse will move it for you to the classes directory:
Desktop -->
workspace -->
QuizProgram -->
bin -->
QuizProgram -->
YourClass.class
Questions.txt <--- Eclipse moves this for you
src -->
QuizProgram -->
YourClass.java
Questions.txt
right.png
And you'll be able to use the getResource() method as you have it written.
Having said that, you'll eventually get to a build system that will do much of this for you but this should get you started.