Search code examples
javafileparent

Why File.getParent() returns a path without slashes in windows?


I have a java programe which works well in linux, but it returns wrong values in windows. I have a File variable and I try to retrieve its parent path with getParent() method. The result in windows is a path without slashes.

...
File store = fileChooser.getSelectedFile ();  
System.out.println(store.getParent()); 
// prints C:UsersMynameDesktopTest
// expected C:/Users/Myname/Desktop/Test

Anyone knows the cause of this problem ?


Solution

  • I found the solution of this problem:

    I used I used replaceAll() method to modify a configuration file, and in the second parameter I put my path (which is C:\Users\Myname\Desktop\Test in windows). It is mentionned in the the Javadoc that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string.

    So to resolve this problem I did:

    ...
    content.replaceAll("root/ca", store.getParent().replaceAll("\\\\", "/") );
    

    It works directly on linux because in linux the default file separator is "/".