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

后端 未结 10 2019
走了就别回头了
走了就别回头了 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:10

    Do you have the option of using

    System.getProperty("file.separator")
    

    to build the string that represents the path?

    0 讨论(0)
  • 2020-12-09 09:11

    With the new Java 7 they have included a class called Paths this allows you to do exactly what you want (see http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html)

    here is an example:

    String rootStorePath = Paths.get("c:/projects/mystuff/").toString();
    
    0 讨论(0)
  • 2020-12-09 09:20

    Shouldn't it be enough to say:

    "path"+File.Seperator+"to"+File.Seperator+"some"+File.Seperator+"file"
    
    0 讨论(0)
  • 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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题