2014-10-20 174 views
1

我正在嘗試創建一個將從終端或命令行運行的程序。你將不得不在參數中提供一個文件名。我希望它能夠獲得程序運行的路徑,然後將文件名追加到它。這將是這樣的:從終端或命令行運行時獲取路徑

public static void main(String[] args) { 
    Scanner scanner = new Scanner(System.in); 
    if (args.length > 0) { 
     if (args[0] instanceof String && !args[0].equals(null)) { 
      if (args[0].equals("compile")) { 
       System.out.println("File to compile:"); 
       String fileName = scanner.next(); 
       String path = /*get the path here*/ + fileName; 
       File textfile = new File(path); 
       if (textfile.exists()) { 
        Compiler compiler = new Compiler(textfile); 
        compiler.compile(); 
       } else { 
        System.out.println("File doesn't exist"); 
       } 
      } 
     } 
    } 
} 
+1

如果文件名不是以「://」或「/」(分別爲Windows和Unix)開頭,則Java將自動使用相對路徑。 – MrHug 2014-10-20 14:13:37

回答

1

這應該爲你工作:

Paths.get("").toAbsolutePath().toString() 

您可以測試通過:

System.out.println("" + Paths.get("").toAbsolutePath().toString()); 
+0

對不起,如果我沒有解釋得很好,但我希望能夠獲得路徑,如果任何最終用戶從任何目錄運行它。我需要能夠在程序通過terminal/cmd運行時獲取用戶所在的cd。 – epicsharp 2014-10-20 14:13:06

+0

好吧,我編輯了我的帖子,它應該爲你工作。 – brso05 2014-10-20 14:32:34

0

如果我理解正確,你正在試圖獲得程序所在的路徑。

如果這樣你就可以嘗試以下方法:

URI path = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath().toURI()); 
1

試試這個:

String path = System.getProperty("user.dir") + "/" + fileName; 
+1

但請記住,路徑可以是絕對路徑(例如'/ bla/bla&filename') – Oncaphillis 2014-10-20 14:25:23

0

更換/*get the path here*/Paths.get(".")應該得到你想要的東西。如果您的參數是同一目錄中的文件名,則不必爲其提供創建File對象的路徑。

你的情況

所以,

File textfile = new File(fileName); 

應該正常工作。