K3NN3TH
K3NN3TH

Reputation: 1496

Passing a file argument in Java

I am wondering how to pass a file as an argument on linux command line.

public class Main {
    public static void main(String[] args){
        System.out.println(args[0]);
    }
}

For the above code if I do:

java -jar myJava.jar blah.txt

It prints blah.txt to the screen.

But I have a sample line of code that looks like this:

java -jar myJava.jar < blah.txt

How am I able to get the value of blah.txt from the above command?

Upvotes: 1

Views: 1527

Answers (2)

Reimeus
Reimeus

Reputation: 159864

Use one of the techniques for reading from System.in where the file is being redirected such as Scanner

Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    ...
 }

Upvotes: 4

Davis Broda
Davis Broda

Reputation: 4135

try the following

java -jar myJava.jar 'blah.txt'

The quotes indicate that the argument is literal.

double quotes will also work, but will not prevent things like variable expansion, so single quotes is better when trying to pass a literal string.

Upvotes: 0

Related Questions