2

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.

Manitoba
  • 8,522
  • 11
  • 60
  • 122
  • Here is the code I use (Without the clean path) http://stackoverflow.com/questions/10204722/java-exec-console/10205644#10205644 – Manitoba Apr 18 '12 at 13:06
  • So what is the criteria for the cleaned path? Only the part after the last '\'? – Qowaz Apr 18 '12 at 12:50

3 Answers3

5

If fileName is your filename string, then something like:

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

should do it...

Se also the API description.

Mathias Schwarz
  • 7,099
  • 23
  • 28
  • 1
    Does not work for all. For instance: input = "/Whatever/mette_e1.mastodon/..\dataset_DataStoreAlfeios.xml"; canonical = "/Whatever/mette_e1.mastodon/..\dataset_DataStoreAlfeios.xml"; – Jean-Yves Jun 02 '22 at 07:14
3

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)

Community
  • 1
  • 1
sp00m
  • 47,968
  • 31
  • 142
  • 252
3

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:\

AlexR
  • 114,158
  • 16
  • 130
  • 208