0

In this stackoverflow.com response I saw how get both at same time, but not separately.

I want to get in java command line a parameter or a stdin redirection.

I solved it in this way:

public static void main(String[] args) {

  String fileInput = "";

  try {
      if (System.in.available() > 0) {
          InputStreamReader isr = new InputStreamReader(System.in);
          int ch;
          while((ch = isr.read()) != -1) {
              //System.out.print((char)ch);
              fileInput += (char)ch;
          }  
      }
  } catch(IOException e) {
      e.printStackTrace();
  }

  if ( ((fileInput.length() > 0) && (args.length > 0)) ||
       ((fileInput.length() == 0) && (args.length != 1)) ||
       ((fileInput.length() == 0) && (args.length == 0))   
     ) {
      System.out.println("Use: myprogram \"string\"");
      System.out.println("Use: myprogram < file");
      System.exit(0); 
  }

But I have a doubt. As Oracle 10 help says: "Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes

Note that while some implementations of InputStream will return the total number of bytes in the stream, many will not. It is never correct to use the return value of this method to allocate a buffer intended to hold all data in this stream.".

My question is: The method available() always will know that there is a std redirection? Will always return > 0 when there is std redirection?

In my tests worked fine, but I don't know if it will work fine in all implementations.

oml
  • 115
  • 2
  • 8

1 Answers1

0

If you're piping from another program, otherprogram | myprogram, the other program might be slow providing data, so you cannot test for that.

For this very reason, it is common for commands, especially on Linux, to specify an argument value of - to indicate that data should be read from STDIN.

E.g.

# No-arg call prints options
myprogram

# Arg not '-' means to use argument value
myprogram "string"

# '-' means to read STDIN
myprogram - < file

otherprogram | myprogram -
Andreas
  • 154,647
  • 11
  • 152
  • 247