epicsharp
epicsharp

Reputation: 405

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

Upvotes: 1

Views: 169

Answers (4)

brso05
brso05

Reputation: 13232

This should work for you:

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

You can test by:

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

Upvotes: 1

Kevin
Kevin

Reputation: 36

Replacing /*get the path here*/ with Paths.get(".") should get you what you want. 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.

So in your case,

File textfile = new File(fileName);

should work as well.

Upvotes: 0

Francesco
Francesco

Reputation: 1802

Try this:

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

Upvotes: 1

Frunk
Frunk

Reputation: 180

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());

Upvotes: 0

Related Questions