0

Sitting here with a bigger java project (for a first year software student) having some troubles creating the correct file path to resources.

I right now have files in the form of .txt, .png, .jpg, and a .gif.

Right now i use paths like this to find a text file:

File userFile = new File("Source Code/files/users.txt");

Or paths like this to create an image loaded in my FX code:

File logoPath = new File("Source code/files/graphics/Streamy_logo.png");
Image logoImage = new Image(logoPath.toURI().toString());
logo.setImage(logoImage);

This works fine in my IDE (IntelliJ), however it doesn't work when i create the project as a Jar file. I think is has to do with the "source code" directory not created in the jar-file, which makes sense now.

Tried to read different subjects, but it seems a bit different if i should use a getResources-method, set a resourceStream or something else.

Can anybody please help me with this. Thank you!

Theodor K
  • 13
  • 5

2 Answers2

0

You can't load files like that in .jar files here's an example on how to read BufferedImages. But first, make sure you have marked the resource folder as a resource folder in IntelliJ by right-clicking the folder in the project view and going down to "Mark directory as" and checking resource root.

    BufferedImage exampleBlock = null;
    try {
        exampleBlock = ImageIO.read(ClassLoader.getSystemResource("exampleBlock.png"));
    } catch (IOException e) {
        e.printStackTrace();
    }

By using this method of getting files all your files will be implemented into the .jar file and you can use them by calling their file name + extension

Linus
  • 1
  • 3
0

For maven or gradle projects, that respects maven directories convention you can simply use

getClass().getResource("/your_file_located_in_src_main_resources.extension").getPath()
Binary Igor
  • 168
  • 1
  • 5