繁体   English   中英

如何从 java 中的命令行参数或标准输入重定向中读取?

[英]How to read from command line parameter or stdin redirection in java?

这个 stackoverflow.com 响应中,我看到了如何同时获得两者,但不是分别获得。

我想在 java 命令行中获取参数或标准输入重定向。

我以这种方式解决了它:

public static void main(String[] args) {

  String fileInput = "";

  try {
      if (System.in.available() > 0) {
          InputStreamReader isr = new InputStreamReader(System.in);
          int ch;
          while((ch = isr.read()) != -1) {
              //System.out.print((char)ch);
              fileInput += (char)ch;
          }  
      }
  } catch(IOException e) {
      e.printStackTrace();
  }

  if ( ((fileInput.length() > 0) && (args.length > 0)) ||
       ((fileInput.length() == 0) && (args.length != 1)) ||
       ((fileInput.length() == 0) && (args.length == 0))   
     ) {
      System.out.println("Use: myprogram \"string\"");
      System.out.println("Use: myprogram < file");
      System.exit(0); 
  }

但我有一个疑问。 As Oracle 10 help says: "Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread或另一个线程。单次读取或跳过这么多字节不会阻塞,但可能会读取或跳过更少的字节

请注意,虽然 InputStream 的某些实现将返回 stream 中的总字节数,但许多不会。 使用这个方法的返回值来分配一个缓冲区来保存这个 stream 中的所有数据是不正确的。

我的问题是:方法 available() 总是会知道有一个标准重定向? 当有标准重定向时总是返回 > 0?

在我的测试中运行良好,但我不知道它是否在所有实现中都能正常运行。

如果您从另一个程序进行管道传输, otherprogram | myprogram otherprogram | myprogram ,另一个程序提供数据的速度可能很慢,因此您无法对此进行测试。

出于这个原因,命令,特别是在 Linux 上,通常会指定参数值-以指示应从 STDIN 读取数据。

例如

# No-arg call prints options
myprogram

# Arg not '-' means to use argument value
myprogram "string"

# '-' means to read STDIN
myprogram - < file

otherprogram | myprogram -

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM