0

I'm creating a java with Gradle, and I can't use it in an app because of error when accessing it resources files.

As said on: Access file in jar file? I'm getting file by using getResource method (I tried both of them)

> Task :App.main() FAILED
Exception in thread "main" java.lang.IllegalArgumentException: URI is not hierarchical
    at java.io.File.<init>(File.java:418)
    at mbe.lib.simple.Library.listFiles(Library.java:27)
    at mbe.app.simple.App.main(App.java:18)

Execution failed for task ':App.main()'.
> Process 'command 'C:/Program Files/Java/jdk1.8.0_112/bin/java.exe'' finished with non-zero exit value 1

Project test.lib.simple:

-- main/java/Library
---- readText : which return string of resources/text.txt
---- listDir: which return File list of the resources/dir
-- main/resources/text.txt
-- main/resources/dir
---- one.txt / two.txt / three.txt
-- test/java/LibraryTest.testRead() : ok displayed
-- test/java/LibraryListTest.testList() : ok displayed getting 3 files.

public class Library {
    public String readText() throws IOException {
        URL url = getClass().getClassLoader().getResource("text.text");
        return Resources.toString(url, StandardCharsets.UTF_8); // guava
    }

    public File[] listFiles() throws URISyntaxException {
        URI uri = getClass().getClassLoader().getResource("dir").toURI();
        File dir = new File(uri);
        return dir.listFiles();
    }
}

Project test.app.simple:

public class App {
    public static void main(String[] args) throws IOException, URISyntaxException {
        Library lib = new Library();
    System.out.println(lib.readText()); // OK 
        Arrays.stream(lib.listFiles()).map(File::getName).collect(Collectors.joining(System.lineSeparator())); // java.lang.IllegalArgumentException: URI is not hierarchical
    }
}

Precisions:

  • I publish my lib on my local maven repo (I have publish the jar with the gradle task publishOnMavenLocal)
  • I searched in the jar and the file is present at the root.

Any idea?

Marcel kobain
  • 153
  • 2
  • 12
  • You'd have to update your answer with the code of main/java/Library.java. – rzwitserloot Jul 10 '20 at 14:37
  • Why are you using the `java.nio.file.*` API to access a _resource_? Resources are not files. Just use `URL#openStream()` or `#getResourceAsStream(String)` and wrap it in a `BufferedReader` to read the lines. Don't forget to close the resource when done with it. – Slaw Jul 10 '20 at 15:24
  • Yes you are right, but actually I think my problem is little more complicated, because in my lib I need to list files of a directory and then read them. (I update the ticket) – Marcel kobain Jul 10 '20 at 16:25
  • There's no _supported_ way to list the embedded resources in a "directory". – Slaw Jul 10 '20 at 20:24
  • realy ? damn ... – Marcel kobain Jul 11 '20 at 08:31
  • So I did an other way without files for my algo, thanks for your feedback. – Marcel kobain Jul 12 '20 at 15:45

0 Answers0