java - ClassLoader.getResource returns odd path (maybe)? -
when loading asset such text file resources folder, common approach use classloader path:
string path = getclass().getclassloader().getresource("file.txt").getpath();
you can use of many readers java has read content of file. reason, paths.get(path)
not happy path:
byte[] content = files.readallbytes(paths.get(path)) -> throws java.nio.file.invalidpathexception when executed
classloader.getresource(...).getpath() returning:
/d:/projects/myapp/build/resources/main/file.txt
paths.get()
doesn't it. apparently ':' after /d
'illegal char'. (note path seems correct, file there)
which 1 causing problem? classloader.getresource()
returning invalid path or paths.get()
acting on nothing?
some time later
seems there multiple different formats paths in java. various frameworks don't appear agree on right , wrong, therefore there various discrepancies between paths create , accept.
in example, paths.get()
in fact not expecting leading slash in path:
/d:/projects/myapp/build/resources/main/vertex.vs.glsl <- evil d:/projects/myapp/build/resources/main/vertex.vs.glsl <- ok
i suppose question is: how sanitise file paths returned classloader.getresource()
use paths.get()
properly? there other differences between 2 file path formats?
- "the common approach" not best :)
- take care path mean: classloader.getresource() returns url, can have path component. however, not valid file-path.
note, there method paths.get(uri) takes uri parameter - the first slash in
/d:/projects/myapp/build/resources/main/file.txt
means, absolute path: see class.getresource - i recommend, use classloader.html#getresourceasstream when want read file
update answer comment: "so why paths.get() not accept absolute path?"
paths.get()
does accept absolute paths.
must pass valid (file-)path - , in case pass url-path directly (which not valid file-path).
- when call:
getclass().getclassloader().getresource("file.txt")
returns url:file:/d:/projects/myapp/build/resources/main/file.txt
- this url consists of schema
file:
- and valid (absolute url)path:
/d:/projects/myapp/build/resources/main/file.txt
- this url consists of schema
- you try use url-path directly file-path, wrong
- thus paths.get(string,..) method throws
invalidpathexception
- thus paths.get(string,..) method throws
to convert url path valid file-path use paths.get(uri) method so:
url fileurl = getclass().getclassloader().getresource("file.txt"); string filepath = paths.get(fileurl.touri()); // have valid file-path: d:/projects/myapp/build/resources/main/file.txt
Comments
Post a Comment