简体   繁体   English

BufferedReader readLine()方法花费了很多时间

[英]BufferedReader readLine() method taking so much time

I am taking InputStream from a Process and reading it through BufferedReader. 我从流程中获取InputStream并通过BufferedReader读取它。 In while loop although, the br is having just one line, it is taking almost 1 minute. 尽管在while循环中,br仅有一行,但几乎要花1分钟。 I checked this by printing before and after as shown in below code. 我通过打印之前和之后进行检查,如下面的代码所示。

String[] sendCommand = { "/bin/bash", "/Users/apple/Downloads/yowsup-e56f2d28f38c7961a2ccf7df588462f1c9588edf/sendmessage.sh"};
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.directory(new File("/Users/apple/Downloads/yowsup-e56f2d28f38c7961a2ccf7df588462f1c9588edf"));
processBuilder.environment().put("PYTHONPATH", "/Users/apple/Downloads/yowsup-e56f2d28f38c7961a2ccf7df588462f1c9588edf");
processBuilder.command(sendCommand);

Process process = processBuilder.start();
process.waitFor();  
InputStream stream = process.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
String temp = null;
System.out.println("before");
long start_time = System.currentTimeMillis();
while ((temp = br.readLine()) != null) 
{
    str = temp;
}
long end_time = System.currentTimeMillis();
long time_taken = end_time-start_time;
System.out.println("after");
System.out.println("Time taken in while loop: "+time_taken/1000);

The result was: 结果是:

before
after
Time taken in while loop: 67

I want to improve the time taken as 1 minute is very slow. 我想改善时间,因为1分钟非常慢。 What are the possible options? 有哪些可能的选择? Is it dependent on what Process I am using? 它取决于我正在使用哪个进程? Please help me. 请帮我。

It's not the reading, it's the writing. 这不是阅读,而是写作。 BufferedReader can't go any faster than the output is produced. BufferedReader速度不会超过生成输出的速度。 If there's nothing to read, it blocks. 如果没有什么可阅读的,它将阻塞。 You're looking at the wrong end. 您正在寻找错误的结局。

NB Your loop is basically pointless, or at best very odd. 注意:你的循环基本上是毫无意义的,或者充其量是很奇怪的。 You're reading every line the process ever produces and throwing away all but the last line. 您正在读取过程中产生的每一行,并丢弃除最后一行以外的所有内容。 Surely you should do something with every line? 当然,您应该对每一行都做些什么?

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

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