解决Mac和Windows之间的路径差异

时间:2017-06-29 17:04:17

标签: java file path directory bufferedwriter

我是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;
}

2 个答案:

答案 0 :(得分:0)

正斜杠" /"必须用于获取文件路径。例如>使用:

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

答案 1 :(得分:0)

您可以使用系统属性来识别您当前正在操作的系统。 更多信息,请访问https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

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

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