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?

  1. "the common approach" not best :)
  2. 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
  3. the first slash in /d:/projects/myapp/build/resources/main/file.txt means, absolute path: see class.getresource
  4. 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
  • you try use url-path directly file-path, wrong

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

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -