简体   繁体   中英

Java - Clean file path

I want to clean the path I use in my App. The path can be modified and sometimes I got something like that:

C:/users/Username/Desktop/\..\..\..\Windows\Web\..\..\Program Files\..\Program Files\..\Python27\

But I would like to have something like:

C:\Python27\

That's an example!

How can I clean the path to get only the necessary part?

Thanks.

If fileName is your filename string, then something like:

String cleanedFilename = new File(fileName).getCanonicalPath();

should do it...

Se also the API description .

You could try using the File.getCanonicalPath() method:

File file = new File("my/init/path");
String path = file.getCanonicalPath();

I haven't test though, tell us back!

EDIT: @MathiasSchwarz is right, use getCanonicalPath() instead of getAbsolutePath() ( link )

Here is the code I have just tried.

new File("c:/temp/..").getCanonicalPath();

It returns 'C:\\', that is right. The parent of c:/temp is indeed c:\\

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