java.lang.IllegalArgumentException: URI is not hierarchical when use a lib as a .jar (gradle without spring)
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?