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

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

    This is what Apache commons-io does, unrolled into a couple of lines of code:

    String separatorsToSystem(String res) {
        if (res==null) return null;
        if (File.separatorChar=='\\') {
            // From Windows to Linux/Mac
            return res.replace('/', File.separatorChar);
        } else {
            // From Linux/Mac to Windows
            return res.replace('\\', File.separatorChar);
        }
    }
    

    So if you want to avoid the extra dependency, just use that.

提交回复
热议问题