Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL getResource not working when in JAR file

Tags:

java

eclipse

jar

My application loads a txt file which is in PROJECTNAME/resource folder.

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) {
        e1.printStackTrace();
}

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(ZipFileSystemProvider.java:87)
        at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:166)
        at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:157)
        at java.nio.file.Paths.get(Unknown Source)
        at ReportSetup$13.mouseReleased(ReportSetup.java:794)

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

like image 592
Shank Avatar asked Aug 26 '16 13:08

Shank


1 Answers

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(
        getClass().getClassLoader().getResourceAsStream("batTemplate.txt"),
        StandardCharsets.UTF_8))) {

    int c;
    while ((c = reader.read()) >= 0) {
        text.append(c);
    }
}

String bat = text.toString();
like image 72
VGR Avatar answered Nov 04 '22 19:11

VGR