Command Line Pipe Input in Java

2019-01-14 13:41发布

问题:

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.

回答1:

By executing "java Read < input.txt" you've told the operating system that for this process, the piped file is standard in. You can't then switch back to the command line from inside the application.

If you want to do that, then pass input.txt as a file name parameter to the application, open/read/close the file yourself from inside the application, then read from standard input to get stuff from the command line.



回答2:

Well, this is typical for reading in a BufferedReader. readLine() returns null when end of stream is hit. Perhaps your infinite loop is the problem ;-)

// try / catch ommitted

String x = null;

while( (x = f.readLine()) != null )
{
   System.out.println(x);
}


回答3:

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();
        }
    }


回答4:

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?

Sorry to bump an old question, but none of the answers so far points out that there is a (shell-only) way to pass back to console input after piping in a file.

If you run the command

{ cat input.txt & cat; } | java Read

then the text from input.txt will be passed to java Read and you will then be dropped back to console input.

Note that if you then press Ctrl+D, you will get the infinite loop of nulls, unless you modify your program to end the loop when it receives null.