简体   繁体   English

Windows 和 Linux 的文件路径名

[英]File path names for Windows and Linux

Below is a path to my Windows directory.下面是我的 Windows 目录的路径。 Normally the path should have \\ instead of // but both seem to work.通常路径应该有 \\ 而不是 // 但两者似乎都有效。

String WinDir = "C://trash//blah//blah";

Same for a Linux path. Linux 路径相同。 The normal should have a / instead of //.正常应该有一个/而不是//。 The below and above snippet work fine and will grab the contents of the files specified.下面和上面的代码片段工作正常,将抓取指定文件的内容。

String LinuxDir = "//foo//bar//blah"

So, both use strange declarations of file paths, but both seem to work fine.因此,两者都使用奇怪的文件路径声明,但两者似乎都可以正常工作。 Elaboration please.请详述。

For example,例如,

 File file = new File(WinDir);`
 file.mkdir();`

Normally, when specifying file paths on Windows, you would use backslashes.通常,在 Windows 上指定文件路径时,您会使用反斜杠。 However, in Java, and many other places outside the Windows world, backslashes are the escape character, so you have to double them up.但是,在 Java 和 Windows 世界之外的许多其他地方,反斜杠是转义字符,因此您必须将它们加倍。 In Java, Windows paths often look like this: String WinDir = "C:\\\\trash\\\\blah\\\\blah";在 Java 中,Windows 路径通常如下所示: String WinDir = "C:\\\\trash\\\\blah\\\\blah"; . . Forward slashes, on the other hand, do not need to be doubled up and work on both Windows and Unix.另一方面,正斜杠不需要加倍并且在 Windows 和 Unix 上都可以使用。 There is no harm in having double forward slashes.使用双正斜杠没有坏处。 They do nothing to the path and just take up space ( // is equivalent to /./ ).它们对路径没有任何作用,只占用空间( //相当于/./ )。 It looks like someone just did a relpace of all backslashes into forward slashes.看起来有人只是将所有反斜杠替换为正斜杠。 You can remove them.您可以删除它们。 In Java, there is a field called File.separator (a String) and File.separatorChar (a char), that provide you with the correct separator ( / or \\ ), depending on your platform.在 Java 中,有一个名为File.separator (一个字符串)和File.separatorChar (一个字符)的字段,它们为您提供正确的分隔符( /\\ ),具体取决于您的平台。 It may be better to use that in some cases: String WinDir = "C:" + File.separator + "trash" + File.separator + "blah" + File.separator + "blah";在某些情况下最好使用它: String WinDir = "C:" + File.separator + "trash" + File.separator + "blah" + File.separator + "blah";

With java.nio.path, you even better get an independent OS path without any concern about path delimiter.使用 java.nio.path,您甚至可以更好地获得独立的操作系统路径,而无需担心路径分隔符。

public class PathsGetMethod {
    public static void main(String[] args) {
        Path path = Paths.get("C:\\Users\\conta\\OneDrive\\", "desktop", "data");
        System.out.println(path); 
        //C:\Users\conta\OneDrive\desktop\data
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM