0

I am using IntelliJ IDEA 2022.2.1 editor. In one of my test case I am reading the file from resource folder using below method getClass().getResource(filename)

I can get the path, but problem is it's always returning with extra forward slash('/') for an instance /C:/Users/test/IdeaProjects/data.json like this.

Due to that extra slash at 0 index. I am getting java.nio.file.InvalidPathException.

Note: this works fine in mac book, This issue is only with window OS.

Any suggestion would be reuired.

Mak
  • 1,068
  • 8
  • 19
  • how do you get that path? Issue is not related to the editor you use I guess. – zapl Oct 11 '22 at 17:47
  • Please show your code to reproduce this issue. – CrazyCoder Oct 11 '22 at 17:53
  • 2
    *I can get the path...* It's not a path. It's a ```java.net.URL``` I would beware of mixing that up with file/path related classes and operations. More often than not, you will need ```getResourceAsStream``` not ```getResource```. Since it's a resource, forget ```File``` and ```Path``` – g00se Oct 11 '22 at 18:07
  • @CrazyCoder I am using below code private String readFileToString(String filename) throws Exception { URL url = getClass().getResource(filename); return new String(Files.readAllBytes(Path.of(url.getPath()))); } If you see there url.getPath() its giving path extra forward slash – Mak Oct 12 '22 at 09:21
  • @g00se even if I use url.toURI() even though it is working. But my question is why it is not working with url.getPath() in windows OS. Why getPath() is giving absolute path in windows and virtual path in Mac OS. – Mak Oct 12 '22 at 10:08
  • Easier ```String text = new String(getClass().getResourceAsStream("/bar").readAllBytes());``` *Why getPath() is giving absolute path in windows and virtual path in Mac OS* What is the *exact* path given by Mac? – g00se Oct 12 '22 at 10:12

0 Answers0