繁体   English   中英

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

[英]Resolving Path Differences Between Mac and Windows

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

必须在此处使用正斜杠“ /”来获取文件路径。 例如。使用:

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

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

但我宁愿使用NIO。 但这是你的选择

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM