Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Piping Input using Java using command line

Tags:

java

input

piping

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 am able to run this code from the command line by typing 'java ReadInput < input.txt' but not by typing the input directly like 'java ReadInput hello'. When I type 'java ReadInput hello' I seem to get stuck in an infinite loop for some reason. Shouldn't it just work in the same way as typing 'java ReadInput < input.txt' but instead just reprint 'hello'?

like image 549
mephisto_ Avatar asked May 07 '11 01:05

mephisto_


People also ask

How does pipe work in CMD?

Pipe is used to combine two or more commands, and in this, the output of one command acts as input to another command, and this command's output may act as input to the next command and so on. It can also be visualized as a temporary connection between two or more commands/ programs/ processes.

What is command line input in Java?

Java Command-Line Arguments This allows data to be available to the program when it is launched. Arguments are passed to the main method's String array parameter Strings[] args and then can be parsed. Consider the program below: public class Example { public static void main(String[] args) {

How do I run Java from the command line?

Type 'javac MyFirstJavaProgram. java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption: The path variable is set). Now, type ' java MyFirstJavaProgram ' to run your program.

Can we use Java in terminal?

Whatever your purpose may be, executing Java code directly from the terminal is a very easy task. In this article, I will show you how you can execute Java directly from your favorite terminal window.


1 Answers

Arguments given on the program's command line don't go to System.in, they go in the args array. You could use something like echo hello | java ReadInput to run the program, or you could modify the program to to look at its args array and treat it as input. (If you use the latter option, you'd probably want to fall back to reading from System.in if there's nothing in args.)

like image 59
Wyzard Avatar answered Oct 18 '22 13:10

Wyzard