簡體   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