Error in URL.getFile ()

I am trying to open a file from a URL.

The URL object is created using the getResource () method of the ClassLoader class. The output URL returned by getResource () is =

file:/C:/users/ 

After using the URL.getFile () method, which returns String as "/ C: / users /", it deletes " file: " just not " / This / gives me an error opening the file using the new FileInputStream. Error: FileNotFoundException

The "/" at the beginning of the file name causes the same problem when getting the path object. Here, the directory value is retrieved from URL.getResource (). Getfile ()

Path Dest = Paths.get (Directory);

Received error: java.nio.file.InvalidPathException: Illegal char <:> at index 2: / C: / Users /

Does anyone encounter such a problem?

+8
java-7
source share
2 answers

Do not use URL.getFile() , it returns the part of the "file" of the URL that does not match the file or the file path name on disk. (It looks like this, but there are many ways you found a mismatch.) Instead, call URL.toURI() and pass the resulting URI to Paths.get()

This should work if your URL points to a real file, not a resource inside a jar file.

Example:

 URL url = getClass().getResource("/some/resource/path"); Path dest = Paths.get(url.toURI()); 
+12
source share

The problem is that your result path contains a leading / .

Try:

 ClassLoader loader = Thread.currentThread().getContextClassLoader(); Path path = Paths.get(loader.getResource(filename).toURI()); 
+2
source share

All Articles