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'?
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.
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) {
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.
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.
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
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With