【问题标题】:Command Line Pipe Input in JavaJava中的命令行管道输入
【发布时间】:2010-11-28 17:28:38
【问题描述】:

这是一段简单的代码:

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

我将其执行为:java Read

一旦 input.txt 完全通过管道传输到程序中,x 就会不断获得无限的空值。为什么呢?在将文件输入代码完成后,有没有一种方法可以使标准输入(命令行)处于活动状态? 我试过关闭流并重新打开,它不起作用。也重置等。

【问题讨论】:

  • 是否对原始代码进行了编辑以考虑接受的答案。因为该答案现在似乎不适用于此代码:该代码不会从 arg 列表中读取文件或答案所暗示的任何事情。在这种情况下,最好保留错误代码以使整个页面更有意义。
  • @Rondo - 不。 Here 是修订版。

标签: java file command-line input pipe


【解决方案1】:

有没有一种方法可以使标准输入(命令行) 文件输入代码完成后是否激活?

很抱歉提出一个老问题,但到目前为止,没有一个答案指出存在 一种(仅限 shell)在文件管道后传递回控制台输入的方法。

如果你运行命令

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

然后来自input.txt 的文本将被传递给java Read,然后您将被退回到控制台输入。

注意,如果你再按Ctrl+D,你会得到nulls的无限循环,除非你修改你的程序来结束循环收到 null。

【讨论】:

    【解决方案2】:

    当该行为空时,您需要终止您的 while 循环,如下所示:

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

    【讨论】:

      【解决方案3】:

      嗯,这对于阅读BufferedReader 来说很典型。 readLine() 在流结束时返回 null。也许你的无限循环是问题;-)

      // try / catch ommitted
      
      String x = null;
      
      while( (x = f.readLine()) != null )
      {
         System.out.println(x);
      }
      

      【讨论】:

        【解决方案4】:

        通过执行"java Read < input.txt",您已经告诉操作系统,对于这个进程,管道文件标准的。您不能从应用程序内部切换回命令行。

        如果您想这样做,则将 input.txt 作为文件名参数传递给应用程序,从应用程序内部自己打开/读取/关闭文件,然后从标准输入读取以从命令行获取内容。

        【讨论】:

        • 感谢您的回复,它澄清了
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-22
        • 2011-08-31
        • 2010-12-03
        • 2021-05-10
        • 1970-01-01
        • 2016-08-22
        相关资源
        最近更新 更多