1

I know how to use string args to get the input from the command-line, and it is working fine with input = args[0] where my input is java.exe program s1.in

But I need to run a compare program in terminal. So my input must have the "<" symbol. However, then I can't get my input values using input = args[1]. When I type this in, the args.length become 0. Why does this happen?

As an aside, does anyone know how to best search for this kind of term in google? Itthink google does not recognize "<" in the search entry.

Thank you

Leigh
  • 28,765
  • 10
  • 55
  • 103
IanIsAFK
  • 77
  • 2

2 Answers2

2

It's because when you use xyzzy <inputfile, your shell runs xyzzy and "connects" that file to your standard input. It then expects you to read that standard input to get your data - you never see the argument because it's removed from the command line (or, more likely, never added to your argument list).

That's why many programs will process a file if given, otherwise they'll read their data from standard input. And that's exactly what you need to do here.

For doing this, you'll probably want something like:

import java.io.*;

class Test {
    public static void main(String args[]) {
        InputStreamReader inp = null;
        Boolean isStdIn = false;

        try {
            if (args.length > 0) {
                inp = new InputStreamReader(new FileInputStream(args[0]));
            } else {
                inp = new InputStreamReader(System.in);
                isStdIn = true;
            }

            // Now process inp.

            if (isStdIn)
                inp.close();

        } catch (Exception e) {
            System.exit(1);
        }
    } 
}

It selects either the file (if available) or the standard input stream for reading.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

Often, the most easy way is to use Scanner:

 Scanner scaner = new Scanner (System.in);
user unknown
  • 35,537
  • 11
  • 75
  • 121