2014-10-20 175 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); 

应该正常工作。