【问题标题】:Resolving Path Differences Between Mac and Windows解决 Mac 和 Windows 之间的路径差异
【发布时间】:2017-12-03 12:14:23
【问题描述】:

我是 Stack Overflow 的新手,对编程也很陌生,所以希望这是有道理的。我正在编写一个在特定目录中创建文件的 java 程序。我的程序在 Windows 上运行并在正确的位置创建一个文件,但它在 Mac 上不起作用。我尝试将反斜杠更改为单个正斜杠,但这不起作用。我应该如何更改代码以使其适用于 Mac 或两者都适用?我在下面放了一些代码。

提前致谢!

为文件创建新路径的类:

try{
        //Create file path
        String dirpath = new ReWriterRunner().getPath()+"NewFiles";

        //Create directory if it doesn't exist
        File path = new File(dirpath);
        if (!path.exists()) {
            path.mkdir();
        }

        //Create file if it doesn't exist
        File readme = new File(dirpath+"\\README.md");
        if (!readme.exists()) {
            readme.createNewFile();
        }

获取用户输入文件放置位置的方法:

public static String getPath(){
    String s;
    Scanner in = new Scanner(System.in);
    System.out.println("Enter the directory name under which the project files are stored.");
    System.out.println("Example: C:\\Users\\user\\work\\jhipstertesting)");
    System.out.println("Use double slashes when typing.");
    s = in.nextLine();
    return s;
}

【问题讨论】:

    标签: java file path directory bufferedwriter


    【解决方案1】:

    您可以使用系统属性来识别您当前正在运行的系统.. 更多信息https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

    但我更喜欢使用 NIO。但这是你的选择

    https://docs.oracle.com/javase/tutorial/essential/io/fileio.html

    【讨论】:

    • 使用系统属性效果很好。感谢您的所有帮助!
    【解决方案2】:

    这里必须使用正斜杠“/”来获取文件路径。例如。> 使用:

    File f = new File("/Users/pavankumar/Desktop/Testing/Java.txt");
    f.createNewFile();
    

    【讨论】:

      猜你喜欢
      • 2012-09-01
      • 1970-01-01
      • 2019-04-23
      • 1970-01-01
      • 1970-01-01
      • 2014-12-22
      • 2021-04-27
      • 2017-04-04
      • 2010-10-29
      相关资源
      最近更新 更多