来自流的不完整数据

时间:2012-01-16 10:32:31

标签: java process stream io inputstream

我正在从流程流中读取数据。基本上,我使用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的大小。我无法找到导致此行为的原因。关于可能导致这种情况的任何提示或指示都将受到高度赞赏。

2 个答案:

答案 0 :(得分:1)

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

然后,在将InputStream包裹在BufferedReader之后访问BufferedReader时,您就会出现问题。因此,您无需获取可从读取器读取的字符的数量,而是获得尚未读入缓冲区的可用字节的数量。


您最好只使用readLine()一次从{{1}}一行阅读。

答案 1 :(得分:1)

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

Inputstream.available()没有达到预期效果:

  

通过下次调用此输入的方法,返回估计值可以从此输入流读取(或跳过)而不阻塞的字节数流。

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

相关问题