Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getResource with parent directory reference

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.

like image 713
Tom Kiley Avatar asked Sep 30 '11 19:09

Tom Kiley


People also ask

How do I reference a file in a parent directory?

To include a file relative to the current source file you should use the full path: require_once dirname(__FILE__) . '/../referenced_file.

What is the difference between Class getResource() and ClassLoader getResource()?

getResource can take a "relative" resource name, which is treated relative to the class's package. Alternatively you can specify an "absolute" resource name by using a leading slash. Classloader resource paths are always deemed to be absolute.

How do I get resources in Java?

The getResource() method of java. lang. Class class is used to get the resource with the specified resource of this class. The method returns the specified resource of this class in the form of URL object.


1 Answers

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);
like image 193
palacsint Avatar answered Oct 01 '22 09:10

palacsint