getResource with parent directory reference

2019-05-02 10:25发布

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.

2条回答
The star\"
2楼-- · 2019-05-02 10:58

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?

查看更多
女痞
3楼-- · 2019-05-02 11:20

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);
查看更多
登录 后发表回答