简体   繁体   English

从终端或命令行运行时获取路径

[英]Get the path when run from terminal or command line

I am trying to make a program that will be run from terminal or command line. 我正在尝试制作一个将从终端或命令行运行的程序。 You will have to supply a file name in the arguments. 您将必须在参数中提供文件名。 I want it to be able to get the path in which the program was run and then append the file name to it. 我希望它能够获取运行程序的路径,然后将文件名附加到该路径。 It would be something like this: 就像这样:

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");
                }
            }
        }
    }
}

This should work for you: 这应该为您工作:

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

You can test by: 您可以通过以下方式进行测试:

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

尝试这个:

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

If i understand you correctly you are trying to get the path where the program is located. 如果我正确理解您的意思,您正在尝试获取程序所在的路径。

if so you can try the following: 如果是这样,您可以尝试以下操作:

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

Replacing /*get the path here*/ with Paths.get(".") should get you what you want. Paths.get(".")替换/*get the path here*/应该可以为您提供所需的内容。 If your argument is a filename in the same directory you don't have to provide a path to it to create the File object. 如果参数是同一目录中的文件名,则无需提供指向它的路径即可创建File对象。

So in your case, 所以就你而言

File textfile = new File(fileName);

should work as well. 应该也可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM