Java Windows 和 Linux 的文件路径名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20979625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:42:21  来源:igfitidea点击:

File path names for Windows and Linux

java

提问by Mason T.

Below is a path to my Windows directory. Normally the path should have \ instead of // but both seem to work.

下面是我的 Windows 目录的路径。通常路径应该有 \ 而不是 // 但两者似乎都有效。

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

Same for a Linux path. The normal should have a / instead of //. The below and above snippet work fine and will grab the contents of the files specified.

Linux 路径相同。正常应该有一个/而不是//。下面和上面的代码片段工作正常,将抓取指定文件的内容。

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();`

采纳答案by Mad Physicist

Normally, when specifying file paths on Windows, you would use backslashes. However, in Java, and many other places outside the Windows world, backslashes are the escape character, so you have to double them up. In Java, Windows paths often look like this: 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. 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. It may be better to use that in some cases: String WinDir = "C:" + File.separator + "trash" + File.separator + "blah" + File.separator + "blah";

通常,在 Windows 上指定文件路径时,您会使用反斜杠。但是,在 Java 和 Windows 世界之外的许多其他地方,反斜杠是转义字符,因此您必须将它们加倍。在 Java 中,Windows 路径通常如下所示:String WinDir = "C:\\trash\\blah\\blah";. 另一方面,正斜杠不需要加倍并且在 Windows 和 Unix 上都可以使用。使用双正斜杠没有坏处。它们对路径没有任何作用,只占用空间(//相当于/./)。看起来有人只是将所有反斜杠替换为正斜杠。您可以删除它们。在 Java 中,有一个名为File.separator(a String) 和File.separatorChar(a char)的字段,可为您提供正确的分隔符(/\),具体取决于您的平台。在某些情况下最好使用它:String WinDir = "C:" + File.separator + "trash" + File.separator + "blah" + File.separator + "blah";

回答by logbasex

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
    }
}