Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.nio.file.InvalidPathException with getPath

Tags:

java

I am using this code

 String path =  getClass().getResource("Template.xls").getPath();

When I run it on my machine (windows), everything is good. I even did system.out.println on the get resource part and on the get path part and the results were:

file:/C:/Eclipse/Netbeans/SoftwareCom/build/classes/assets/Template.xls

/C:/Eclipse/Netbeans/SoftwareCom/build/classes/assets/Template.xls

However I am getting the following error reports from some users

java.nio.file.InvalidPathException: Illegal char <:> at index 4:
file:\C:\Software%20Com\SoftwareCom.exe!\assets\Template.xls

Iam not sure whats happening or why would it work for some and not others

Any pointers?

like image 661
Snake Avatar asked Dec 05 '22 00:12

Snake


2 Answers

To answer this question properly, it would be helpful to know what you want to do with the path information. To read the file, you don't need the path. You could just call

getClass().getResourceAsStream("Template.xls")

If you really want to know the path, you should call

URL url = getClass().getResource("Template.xls");
Path dest = Paths.get(url.toURI());

This might cause problems as you seem to pack your java files in a windows executable. See Error in URL.getFile()

Edit for your comment:

As I wrote above, you don't need the path of the source to copy. You can use

getClass().getResourceAsStream("Template.xls")

to get the content of the file and write the content to whereever you want to write it. The reason for failing is that the file in your second example is contained within an executable file:

 file:\C:\Software%20Com\SoftwareCom.exe

as can be seen from the path:

file:\C:\Software%20Com\SoftwareCom.exe!\assets\Template.xls

The exclamation mark indicates that the resource is within that file. It works within Netbeans because there the resource is not packed in a jar, but rather is a separate file on the filesystem. You should try to run the exe-version on your machine. It will most likely fail as well. If you want more information or help, please provide the complete code.

like image 65
Guenther Avatar answered Dec 06 '22 18:12

Guenther


I faced this same issue and go around it by using the good ol' File API

URL url = MyClass.class.getClassLoader().getResource("myScript.sh");
Path scriptPath = new File(url.getPath()).toPath();

And it worked!

like image 20
E.S. Avatar answered Dec 06 '22 19:12

E.S.