Hi everyone,

I'm having some trouble creating an executable jar file that accesses data txt files when running.

I've written a program using Netbeans that reads in both images and data and uses this data while the program is running. But when I try to run the program using the jar file that is automatically created in the dist folder, the images show up just fine, but it hasn't been able to read in the data.

Here's how the directory looks in Netbeans:

ProgramName 
    SourcePackages
        PackageName
            VariousJAVAfiles
        PackageName.resources.data
            VariousTXTfiles
        PackageName.resources.images
            VariousJPGfiles

I'm guessing that I have to do something with the libraries, and I've also heard something about using URL objects, but I'm still confused about what to do.

Any advice on what I'm missing here would be great, thanks!

Recommended Answers

All 2 Replies

Have a look at your jar using a standard zip file utility (whichever you prefer) and check the exact path and file names for the files you need. If you're using Windows, watch out for upper/lower case in the names - the Windows file system is not case sensitive, but opening a file from a jar in Java is.
You don't really need URLs, something as simple as this will work:

BufferedImage image = ImageIO.read(getClass().getResource("/dir/file.png"));

or use
public InputStream getResourceAsStream(String name)
from the Class class to read text, eg

InputStream in = getClass().getResourceAsStream("/stuff.txt");

Thanks James. I took your advice and used InputStream rather than FileReader to get the data out of a text file and its working fine now.

InputStream is = getClass().getResourceAsStream( "file.txt" );
InputStreamReader isr = new InputStreamReader( is );
BufferedReader br = new BufferedReader( isr );
String line = br.readLine();

while( line != null )
{
    arrayList.add( line );
    line = br.readLine();
}

br.close();
isr.close();
is.close();
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.