0

I would like to put ressources in my JAR file but, there is a problem when I want to use it. If I show the path with this code :

JOptionPane.showMessageDialog(null, MyStaticClass.class.getResource("/ressources/") + "file.File" + i, "OK", JOptionPane.INFORMATION_MESSAGE);
                File file = new File(MyStaticClass.class.getResource("/ressources/") + "file.File" + i);

The result of messagebox is jar:file:/home/clement/Bureau/Untitled.jar!/ressources/niveau.Niveau1 and the exeption

java.io.FileNotFoundException: jar:file:/home/clement/Bureau/Untitled.jar!/ressources/file.File1 (No file or folder of this type)

The files are in the src folder in src/ressources/file.File1

John .H
  • 1
  • 1

1 Answers1

0

getResourceAsStream() returns an InputStream. Your code basically tries to find file '/ressources/' which is not a file but a directory, so getResourceAsStream() returns null for it.

There is no point in printing an InputStream. What you could do is something like this:

InputStream is = MyStaticClass.class.getResourceAsStream("/ressources/" + "file.File1")

And then read its contents (for example, using InputStream's read() methods, or wrap it with an InputStreamReader and use it's read(). It's hard to give more advice as I don't know what you'd like to do with what you read.

An update for updated question code follows

getResource() returns a URL instance, which does not suit for printing as well (and for concatenating using + operator). But you can convert it to File instance if you like with help of getFile() method:

File file = new File(MyStaticClass.class.getResource("/ressources/" + "file.File" + i).getFile());

Please also note that getResource() is called on full resource name and not just directory name.

Then you could work with that File instance.

But if you just want to read the resource contents, you could do something like the following (with no need to get URL instance):

InputStream is = MyStaticClass.class.getResourceAsStream("/ressources/" + "file.File1")
Scanner scanner = new Scanner(new InputStreamReader(is, "utf-8"));
try {
    if (scanner.hasNextLine()) {
        System.out.println(scanner.nextLine());
    }
} finally {
    scanner.close();
}

This example assumes that your file is a text file and has at least one line. It prints that line to the console.

Roman Puchkovskiy
  • 11,415
  • 5
  • 36
  • 72