getResource with parent directory reference
Asked Answered
R

2

5

I have a java app where I'm trying to load a text file that will be included in the jar.

When I do getClass().getResource("/a/b/c/"), it's able to create the URL for that path and I can print it out and everything looks fine.

However, if I try getClass().getResource(/a/b/../"), then I get a null URL back.

It seems to not like the .. in the path. Anyone see what I'm doing wrong? I can post more code if it would be helpful.

Ruphina answered 30/9, 2011 at 19:55 Comment(1)
This question answers the question I was coming to search for. I have a getResource("../icons/SomeIcon.png") returning null when loading from a jar but properly returning the resource when loading from the filesystem. It sucks that Java isn't resolving the .. in both cases.Differentiate
A
6

The normalize() methods (there are four of them) in the FilenameUtils class could help you. It's in the Apache Commons IO library.

final String name =  "/a/b/../";
final String normalizedName = FilenameUtils.normalize(name, true); // "/a/"
getClass().getResource(normalizedName);
Adore answered 30/9, 2011 at 23:2 Comment(2)
Awesome this worked. I used the normalize(name,true) method to keep unix style slashes(/) on windows systems. Thank You!Ruphina
@Trejkaz: Thank you for the edit suggestion! Unfortunately it was rejected by others and I have to edit it manually. To compensate your lost +2 points I've checked your posts and upvoted a few of them.Adore
B
2

The path you specify in getResource() is not a file system path and can not be resolved canonically in the same way as paths are resolved by File object (and its ilk). Can I take it that you are trying to read a resource relative to another path?

Bosquet answered 30/9, 2011 at 20:6 Comment(1)
Ya so I'm getting parts of the path from different places in the code, so I when I combine the strings they have ".."'s in them. I'm not trying to break above the base directory I get with getResource("/"). The resource I'm trying to read is relative to another path, but still inside the jar and something that I could read if I manually removed the ".." from the path. Maybe that's what I'll have to do.Ruphina

© 2022 - 2024 — McMap. All rights reserved.