Entering pipelines using Java using the command line

public class ReadInput {
    public static void main(String[] args) throws IOException {
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        String x = null;  
        while( (x = input.readLine()) != null ) {    
            System.out.println(x); 
        }    
    }
}  

I can run this code from the command line by typing 'java ReadInput <input.txt', but not by entering the input directly, like 'java ReadInput hello'. When I type "java ReadInput hello", for some reason I am stuck in an infinite loop. Shouldn't this work just like the input 'java ReadInput <input.txt', but instead just retype 'hello' instead?

+5
source share
4 answers

, , System.in, args. - echo hello | java ReadInput , , args . ( , , , System.in, args .)

+6

java ReadInput hello, - System.in, , -. , "hello" args main().

( ), main(). , java ReadInput hello, args[0] "hello".

, System.out.println() ( , ). main():

if (args.length > 0) System.out.println(args[0]);
+3

, .

...

java ReadInput < input.txt

... , java:

java ReadInput

< input.txt (System.in).

System.in.readLine(), , , . , , ( ). , , , , .

JVM - (System.in). :

java ReadInput "Input number one" "Input number two"

. args:

   public static void main(String[] args) throws IOException {
          System.out.println(args.length); //3
          System.out.println(args[0]); //"ReadInput"
          System.out.println(args[1]); //"Input number one"
          System.out.println(args[2]); //"Input number two"
   }

With the code you provided, the program will exit when the result of the call to readLine () returns null. I believe that you can just press Enter on a line to send an empty line and end the program. If not, you may need to fix the program to check for an empty string (input.readLine (). Equals ("")).

Hope this helps.

+3
source

Complete standard input with

Ctrl-D  :  Linux/Unix 
Ctrl-Z (or F6) and "Enter" : Windows.

Or install . special EOF symbol

+1
source

All Articles