2

Many commands in Linux take input one of two ways, stdin, or as an argument to a file. Examples

echo "text from stdin" | lpr

lpr filename.txt

echo "text from stdin" | nl

nl filename.txt

The same is true with awk, sed, grep, and many others. How can the same behavior happen from a command line app written in Java? I believe System.in represents stdin. Reading stdin is not difficult. Reading from a file is not difficult, but how can the app act accordingly to how it was called on the command line?

BullShark
  • 85
  • 2
  • 4
  • 12

4 Answers4

0

You process the parameters of your main(String[] args) method. If an argument is supplied, args[0] will be non-empty, so you can assume/verify it's a filename. Otherwise, assume/verify input is provided via stdin.

In code:

 public static void main(String[] args) {
  if (args.length > 0) {
       String filename = args[0];
       ... // process the file
  }
  else { 
     Scanner sc = new Scanner(System.in);
     ... // process STDIN
   }
 }
Jeen Broekstra
  • 21,642
  • 4
  • 51
  • 73
0

It is just programming. For example:

   public class Main {

       public void run(OutputStream out) {
           // Write output to 'out'
       }

       public static void main(String[] args) {
           if (args.length == 1) {
               try (FileOutputStream out = new FileOutputStream(args[0])) {
                   new Main().run(out);
               }
           } else {
               new Main().run(System.out);
           }
       }
    }

This version assumes that the first argument is the output filename, and writes to standard output if no filename is given. You could do the same thing for standard input, and you could process the arguments differently.


Note: instead of using an out parameter, you could use System.setOut(...) to modify the JVM's System.out "variable". But I prefer doing it this way because it makes the application logic more reusable. (Consider the case where you wanted to embed / use the Main class in a larger application ... that used System.out for other purposes.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

You can do what typical unix programs do... check the commandline arfuments (passed in to the main(String[] args) method, and if the appropriate input file is not given then use System.in.

rolfl
  • 17,539
  • 7
  • 42
  • 76
0

Basically, you have to parse arguments passed to your java app. These arguments will indicate your program's logic what to do with the information passé to stdin.

You can parse arguments the simple way as shown here http://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html

Or you can use robust libraries like those mentioned here

How to parse command line arguments in Java?

Community
  • 1
  • 1