简体   繁体   English

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

[英]Resolving Path Differences Between Mac and Windows

I am new to Stack Overflow and fairly new to programming, so hopefully this makes sense. 我是Stack Overflow的新手,还是编程的新手,所以希望这是有意义的。 I am writing a java program that creates a file in a specific directory. 我正在编写一个在特定目录中创建文件的Java程序。 My program works on Windows and creates a file in the right location, but it does not work on Mac. 我的程序可在Windows上运行,并在正确的位置创建文件,但在Mac上则无法运行。 I have tried changing the backslashes to a single forward slash, but that doesn't work. 我曾尝试将反斜杠更改为单个正斜杠,但这不起作用。 How should I change the code so that it works for Mac or ideally for both? 我应该如何更改代码以使其适用于Mac或理想地适用于两者? I've put some of the code below. 我在下面放了一些代码。

Thanks in advance! 提前致谢!

Class that creates new path for file: 为文件创建新路径的类:

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();
        }

Method that gets user input on where to put file: 获取用户输入文件放置位置的方法:

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

Forward slash "/" must be used to get the file path here. 必须在此处使用正斜杠“ /”来获取文件路径。 for ex.> Use: 例如。使用:

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

you can use system properties to identify the system you are currently operating on .. more info at https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html 您可以使用系统属性来标识当前正在运行的系统。更多信息, 访问https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

but i would prefer using NIO. 但我宁愿使用NIO。 but that is your choice 但这是你的选择

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

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

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