从终端或命令行运行时获取路径
问题描述:
我正在尝试创建一个将从终端或命令行运行的程序。你将不得不在参数中提供一个文件名。我希望它能够获得程序运行的路径,然后将文件名追加到它。这将是这样的:从终端或命令行运行时获取路径
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");
}
}
}
}
}
答
如果我理解正确,你正在试图获得程序所在的路径。
如果这样你就可以尝试以下方法:
URI path = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath().toURI());
答
试试这个:
String path = System.getProperty("user.dir") + "/" + fileName;
+1
但请记住,路径可以是绝对路径(例如'/ bla/bla&filename') – Oncaphillis 2014-10-20 14:25:23
答
更换/*get the path here*/
与Paths.get(".")
应该得到你想要的东西。如果您的参数是同一目录中的文件名,则不必为其提供创建File对象的路径。
所以,
File textfile = new File(fileName);
应该正常工作。
如果文件名不是以“://”或“/”(分别为Windows和Unix)开头,则Java将自动使用相对路径。 –
MrHug
2014-10-20 14:13:37