LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Linux command input done in Java (https://www.linuxquestions.org/questions/programming-9/linux-command-input-done-in-java-4175474827/)

fakie_flip 08-26-2013 10:31 PM

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


Code:

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?

kbp 08-27-2013 12:31 AM

I haven't needed to often but in the past I've just tested whether stdin was a pipe and if not then check for data passed via argument .. here's a perl fragment that may clarify:
Code:

if ( -p STDIN ) {

  while (<STDIN>) {
    push(@pids, (split(/ /, $_)));
  }

}
else {

  $numArgs = @ARGV;
  if ( $numArgs > 0 ) {

    @pids = @ARGV;
    chomp @pids;

  }
...


NevemTeve 08-27-2013 02:36 AM

Check the number of arguments (argv.length). If positive, there are parameters (filenames), otherwise read strin.


All times are GMT -5. The time now is 01:12 AM.