Txt file not found when generating .jar file

6

I have a Java application, this application has images, and I had the same problem: when I generated the .jar (executable) file the images did not appear, but if I were to run directly in NetBeans, it would appear. I solved the problem by putting the image inside a folder I created (data) inside the scr folder, and in the code I did:

new ImageIcon(getClass().getResource("/dados/img.jpg"));

This solved the problem, now the deal is with .txt file, how do I do this? I need to read a txt, in NetBeans it finds the right file, however in the generated jar file it is not found

EDIT

File arq = new File("src/dados/arq.txt");
    
asked by anonymous 28.11.2015 / 21:17

1 answer

12

If txt is inside the jar, File will not work because the txt file only exists inside the jar, and does not exist outside it, since File works with URLs of files in the current operating system. To do this, rescue using the following:

InputStream in = getClass().getResourceAsStream("/dados/arq.txt");
BufferedReader input = new BufferedReader(new InputStreamReader(in));

Then just scan the BufferedReader using a repeat loop .

Reference:

How to read a file from a jar file?

Including a text file inside a jar and reading it

    
28.11.2015 / 22:01