我想要将文本文件写入和读取(分别)到与我的程序不同的目录中。当我指定一个要写入或读取的目录时,我应该使用正斜杠还是反斜杠来标识文件路径?
使用正斜杠将使它独立于系统。为简单起见,我建议坚持使用它。
如果您曾经向用户显示路径,请考虑使用 java.io.File.separator
。你不想让 Windows 用户感到惊讶。他们是一个神经质的群体。
java.io.File.separator
(和 separatorChar
)。 - T.J. CrowderpathSeparator
和 pathSeparatorChar
了 :) - Paul Draper我从未在任何地方看到过这个被记录下来,但是JDK类允许您在Windows或其他操作系统上使用斜杠。 (您可以在JDK源代码中看到这一点,在那里它明确为您转换路径分隔符。)
官方上说 — 并且在任何UI中都应该如此 — 您应该使用 file.separator
系统属性, 可通过 System.getProperty
获得(标准系统属性列表在System.getProperties
的文档中有记录):
String sep = System.getProperty("file.separator");
...并且还可以通过static
字段进行访问。它们也可以作为File.separator
(以及File.separatorChar
)使用。
您还可以使用java.io.File
类的各种功能来组合和拆分路径,或使用java.nio.file
中的接口和类的各种功能。
java.nio.file
的注释。 - T.J. CrowderSystem.getProperty("file.separator")
(在UNIX上返回 /
),而不是 System.getProperty("path.separator")
(在UNIX上返回 ;
)。 - Luke您可以使用任意一种符号。
如果您使用 /
,则只需要一个斜杠。
如果您使用 \
,则需要使用 \\
。也就是说,您需要转义它。
您还可以使用 java.nio.Path
类的 resolve()
方法来将目录/文件添加到现有路径中。这避免了使用正斜杠或反斜杠的麻烦。然后您可以通过调用 toAbsolutePath()
方法,再接着调用 toString()
来获取绝对路径。
SSCCE:
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathSeperator {
public static void main(String[] args) {
// the path seperator for this system
String pathSep = System.getProperty("path.separator");
// my home directory
Path homeDir = Paths.get(System.getProperty("user.home"));
// lets print them
System.out.println("Path Sep: " + pathSep);
System.out.println(homeDir.toAbsolutePath());
// as it turns out, on my linux it is a colon
// and Java is using forward slash internally
// lets add some more directories to the user.home
homeDir = homeDir.resolve("eclipse").resolve("configuration");
System.out.println("Appending more directories using resolve()");
System.out.println(homeDir);
}
}
你应该使用 /
例如 C:/User/...
/
作为路径分隔符,这样你的应用程序就可以跨操作系统运行。 - Luiggi Mendoza