Is there a Java utility which will convert a String path to use the correct File separator char?

后端 未结 10 2109
走了就别回头了
走了就别回头了 2020-12-09 08:54

I have developed a number of classes which manipulate files in Java. I am working on a Linux box, and have been blissfully typing new File(\"path/to/some/file\");

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-09 09:21

    A "/path/to/some/file" actually works under Windows Vista and XP.

    new java.io.File("/path/to/some/file").getAbsoluteFile()
    
    > C:\path\to\some\file
    

    But it is still not portable as Windows has multiple roots. So the root directory has to be selected in some way. There should be no problem with relative paths.

    Edit:

    Apache commons io does not help with envs other than unix & windows. Apache io source code:

    public static String separatorsToSystem(String path) { 
        if (path == null) {
         return null;
        }
        if (isSystemWindows()) {
          return separatorsToWindows(path);
        } else {
          return separatorsToUnix(path);
        }
    }
    

提交回复
热议问题