本文介绍了Windows和Linux的文件路径名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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.

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

因此,两者都使用奇怪的文件路径声明,但两者似乎都运行正常。请详细说明。

So, both use strange declarations of file paths, but both seem to work fine. Elaboration please.

例如,

文件文件=新文件(WinDir) ;
file.mkdir();

推荐答案

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

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和Linux的文件路径名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 01:57