【问题标题】:Forward slash or backslash?正斜杠还是反斜杠?
【发布时间】:2013-11-14 17:51:10
【问题描述】:

我正在寻找(分别)在与我的程序不同的目录中写入和读取文本文件。当我指定要写入或读取的目录时,我应该使用正斜杠还是反斜杠来标识文件路径?

【问题讨论】:

  • 使用/,这样您的应用程序将独立于操作系统。
  • 不要将路径硬编码到您的程序中,因此它将与安装无关。

标签: java text file-io slash


【解决方案1】:

你可以使用任何一个。

如果您使用/,那么您只需要一个斜杠。
如果使用\,则需要使用\\。也就是说,你需要逃避它。

您也可以使用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);

    }
}  

【讨论】:

    【解决方案2】:

    我从来没有在任何地方找到它记录,但是 JDK 类允许您使用斜杠,无论您是否在 Windows 上。 (您可以在 JDK 源代码中看到这一点,它会为您显式转换路径分隔符。)

    正式地——当然在你正在做的任何用户界面中——你应该使用file.separatorsystem property,它可以通过System.getProperty获得(标准系统属性列表记录在in the docs for System.getProperties):

    String sep = System.getProperty("file.separator");
    

    ...也可以通过static 字段使用File.separator(和File.separatorChar)。

    您还可以使用the java.io.File class 的各种功能来组合和拆分路径,和/或java.nio.file 中的接口和类的各种功能。

    【讨论】:

    • @LittleChild:谢谢,添加了关于java.nio.file 的注释。
    • 我相信您可能想要引用 System.getProperty("file.separator")(在 UNIX 上返回 /),而不是 System.getProperty("path.separator")(在 UNIX 上返回 ;
    【解决方案3】:

    使用正斜杠将使其独立于系统。为简单起见,我会坚持这样做。

    如果您曾经向用户显示路径,请考虑使用java.io.File.separator。您不想让那些 Windows 用户感到惊讶。他们是一群神经质的人。

    【讨论】:

    • +1 我一直忘记java.io.File.separator(和separatorChar)。
    • @T.J.Crowder。更不用说pathSeparatorpathSeparatorChar :)
    • @Paul:是的,但这些是用于类路径,而不是文件路径。
    【解决方案4】:

    你应该使用 /

    例如 C:/User/...

    【讨论】:

    • 如果您回答why,您的回答会大大提高?
    • 有时需要反斜杠,但出于可移植性考虑,最好避免公开共享代码。根据我的经验,它很少有用或没有必要,即使在 Windows 上开发也是如此。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多