【问题标题】:Incomplete data from a stream流中的不完整数据
【发布时间】:2012-02-11 07:38:56
【问题描述】:

我正在从流程流中读取数据。基本上,我使用 Runtime.exec API 运行进程并获取进程输入流。

Runtime rt = Runtime.getRuntime();
process = rt.exec("C:/cygwin/home/grec.exe");
InputStream is = process.getInputStream();

然后我将进程的输出收集为 --

            BufferedReader in = new BufferedReader(is);         
            char[] ls = new char[s.available()];
            ls.read(ls);
            String output = new String(ls);

但是,当我打印字符串输出时,我得到了 --

  break [loc]     Add a breakpoint at [file:]line or template
  callflow [val]  Enable call flow tracing
  next            Execute the over instruction, stepping over calls
  over            Execute the current instruction hierarchy

但实际输出是--

  break [loc]     Add a breakpoint at [file:]line or template
  callflow [val]  Enable call flow tracing 
  next            Execute the over instruction, stepping over calls
  over            Execute the current instruction hierarchy
  print <xpath>   Print the value of an XPath expression
 profile [val]   Turn profiler on or off
 reload          Reload the script contents
 run             Restart the script
 step            Execute the next instruction, stepping into calls
 verbose         Turn on verbose (-v) output logging
 where           Show the backtrace of template calls
 quit            Quit debugger

也就是说,输出的一部分被截断,但代码没有抛出异常。我尝试增加 BufferedReader 的大小并增加数组 ls 的大小。我无法找到这种行为的原因。任何关于可能是什么原因的提示或指示将不胜感激。

【问题讨论】:

  • 您的代码示例中的s 是什么?也许我忽略了一些东西,但是怎么样:OutputStream out = process.getOutputStream(); BufferedReader bufferedOut = new BufferedReader(out);
  • 其实我在做同样的事情。这就是我正在做的——
  • 这里实际上s代表InputStream。即--InputStream s = process.getInputStream();
  • 为什么不使用in.readline()?为什么要创建 char 数组?

标签: java process stream io inputstream


【解决方案1】:

使用循环处理所有信息并读取到流的末尾。

Inputstream.available() 没有达到您的预期:

返回一个估计可以在下一次调用此输入的方法时从该输入流无阻塞读取(或跳过)的字节数流。

http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html#available%28%29

【讨论】:

    【解决方案2】:

    您错误地假设available() 告诉您实际可用的字节数/字符数。事实上,它告诉您至少有很多可用......它可能是错误的,因为它是一个估计值。

    然后,在将InputStream 包装在BufferedReader 中后,您会通过访问InputStream 来使问题复杂化。因此,不是获取可以从阅读器读取的 characters 数量,而是获取尚未读入缓冲区的可用 bytes 数量。


    您最好使用readLine() 一次从BufferedReader 读取一行。

    【讨论】:

    • 您好斯蒂芬,感谢您的澄清。现在我明白了我的代码中的错误。我尝试在我的代码中使用 BufferedReader.readLine API。但是,在这里我面临另一个问题。我的进程输出是 -- sdb: The SLAX Debugger (version 0.9.6) Type 'help' for help (sdb)
    • 最后一行是。在这种情况下,readLine 调用只是挂起,没有给出任何异常。
    • 进程输出总是包含 作为最终的 putput。它正确获取所有行,但始终挂在最后一行,并且不会从最后一次调用 readLine 返回。
    • 原因是最后一行还没有换行符。如果你想能够处理它,你需要一次处理一个角色,并适当地处理“提示”。
    • 感谢您的意见..非常感谢。但是你能用代码更详细地解释一下吗?如何在不导致 readLine 挂起的情况下处理最后一行。此外,进程可能会因行数而异。所以我该如何以通用方式处理这个问题--
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 2013-02-21
    相关资源
    最近更新 更多