Shank Shank - 4 years ago 255
Java Question

URL getResource not working when in JAR file

My application loads a txt file which is in


enter image description here

Here is how I'm loading the file:

URL url = getClass().getClassLoader().getResource("batTemplate.txt");
java.nio.file.Path resPath;
String bat = "";

try {
resPath = java.nio.file.Paths.get(url.toURI());
bat = new String(java.nio.file.Files.readAllBytes(resPath), "UTF8");
} catch (URISyntaxException | IOException e1) {

NOTE: This works when I run from Eclipse, and doesn't when I Export to a Jar file (Extract required lib. into generated JAR).
I know that the file is being extracted because its in the JAR file. Also the images work.

enter image description here

Error MSG:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException:
Illegal character in path at index 38: file:/C:/DataTransformation/Reports Program/ReportsSetup.jar
at com.sun.nio.zipfs.ZipFileSystemProvider.uriToPath(
at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(
at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(
at java.nio.file.Paths.get(Unknown Source)
at ReportSetup$13.mouseReleased(

I also looked at the similar problem here, however they refer to file/URL outside JAR file.

Answer Source

A .jar entry is not a file; it is part of the .jar archive. It is not possible to convert a resource to Path. You’ll want to read it using getResourceAsStream instead.

To read all of it, you have a few options. You can use a Scanner:

try (Scanner s = new Scanner(getClass().getClassLoader().getResourceAsStream("batTemplate.txt"), "UTF-8")) {
    bat = s.useDelimiter("\\Z").next();
    if (s.ioException() != null) {
        throw s.ioException();

You can copy the resource to a temporary file:

Path batFile = Files.createTempFile("template", ".bat");
try (InputStream stream = getClass().getClassLoader().getResourceAsStream("batTemplate.txt")) {
    Files.copy(stream, batFile);

You can simply read the text from an InputStreamReader:

StringBuilder text = new StringBuilder();
try (Reader reader = new BufferedReader(
    new InputStreamReader(
        StandardCharsets.UTF_8))) {

    int c;
    while ((c = >= 0) {

String bat = text.toString();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download