Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Command Line Pipe Input in Java

Here is a simple piece of code:

import java.io.*;
public class Read {
 public static void main(String[] args) {
     BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
  while(true)
  {
   String x = null;
   try{
    x = f.readLine();
   }
   catch (IOException e) {e.printStackTrace();}
   System.out.println(x);
  }
 }
}

I execute this as : java Read < input.txt

Once the input.txt is completely piped into the program, x keeps getting infinite nulls. Why is that so? Is there a way by which I can make the Standard In(Command Line) active after the file being fed into the code is done? I've tried closing the stream and reopening, it doesn't work. Reset etc also.

like image 764
TJ- Avatar asked Sep 16 '09 07:09

TJ-


People also ask

What is command line input in Java?

The java command-line argument is an argument i.e. passed at the time of running the java program. The arguments passed from the console can be received in the java program and it can be used as an input. So, it provides a convenient way to check the behavior of the program for the different values.

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.

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.

What does Ctrl C do in Java?

ctrl c is used to kill a process. It terminates your program. ctrl z is used to pause the process. It will not terminate your program, it will keep your program in background.


1 Answers

You need to terminate your while loop when the line is null, like this:

    BufferedReader in = null;
    try {
        in = new BufferedReader(new InputStreamReader(System.in));
        String line;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
    }
    catch (IOException e) {
        logger.error("IOException reading System.in", e);
        throw e;
    }
    finally {
        if (in != null) {
            in.close();
        }
    }
like image 132
dogbane Avatar answered Sep 28 '22 11:09

dogbane