我正在嘗試創建一個將從終端或命令行運行的程序。你將不得不在參數中提供一個文件名。我希望它能夠獲得程序運行的路徑,然後將文件名追加到它。這將是這樣的:從終端或命令行運行時獲取路徑
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");
}
}
}
}
}
如果文件名不是以「://」或「/」(分別爲Windows和Unix)開頭,則Java將自動使用相對路徑。 –
MrHug
2014-10-20 14:13:37