开发者

Java command line input with heredoc

I have a frustratingly simple problem: I need to write a program that accepts input of the form:

cat << EOF | java myProgram.java
> 1 2 3 4
> 5 6 7 8
> etcetera
> EOF

B开发者_JAVA百科ut my args[] is always empty when I try to do anything with it in main(). Even cat << EOF | echo followed by input doesn't produce any output at the terminal. What am I doing wrong here?


Use the standard input stream:

public static void main(String[] args) throws Exception {
  InputStreamReader inputReader = new InputStreamReader(System.in);
  BufferedReader reader = new BufferedReader(inputReader);
  String line = null;
  while ((line = reader.readLine()) != null) {
    System.out.println(line);
  }
  reader.close();
  inputReader.close();
}


You didn't provide any arguments to the program, so of course args[] is empty.

You can read the heredoc from System.in.

You seem confused about the difference between arguments (args[]) and stdin (System.in).

echo writes its arguments (args[]) to stdout, e.g.:

$ echo foo bar
foo bar

cat writes its stdin (System.in) to stdout, e.g.:

$ cat << EOF
> foo bar
> EOF
foo bar

or

$ echo foo bar | cat     # Useless use of cat
foo bar

Your cat << EOF | echo example doesn't work because echo does not read stdin.

Also, your use of cat is useless. You can just write

$ java myProgram.java << EOF
> 1 2 3 4
> 5 6 7 8
> etcetera
> EOF
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜