简体   繁体   中英

Resolve a path name with .. parent directory specifiers (“dot dot”) without resolving symlinks

Given a path like /a/./b/c/../d , I would like to remove all the "current directory" indicators (ie, period) and "parent directory" indicators (ie, ..), giving a/b/d .

I could use File.getCanonicalPath() , but that also resolves symlinks, which I don't want.

Any simple way? That is, simpler than writing a tokenizer and handling it all myself.

Bonus points if you can tell me what the right name for '.' and '..' are in this context.

Guava also has this as Files.simplifyPath(String) . Your best bet, though, (if you can use JDK7) is to represent your path as a Path and use Path.normalize() to get the normalized version.

You can use FilenameUtils.normalize() in the Apache Commons IO library - see javadoc here .

"Dot" ( . ) is the current directory and "dot dot" ( .. ) is the parent directory - read up on unix directories .

Have also a look at this question (Java 7 or newer): Java: how to normalize paths with nio Path?

The solution is great, but it is not portable (it will not work on Windows machines).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM