Java Can';无法从Runtime.exec()获取输出
我已经编写了一段代码,通过Java在shell上执行命令:Java Can';无法从Runtime.exec()获取输出,java,shell,Java,Shell,我已经编写了一段代码,通过Java在shell上执行命令: String filename="/home/abhijeet/sample.txt"; Process contigcount_p; String command_to_count="grep \">\" "+filename+" | wc -l"; System.out.println("command for counting contigs "+command_to
String filename="/home/abhijeet/sample.txt";
Process contigcount_p;
String command_to_count="grep \">\" "+filename+" | wc -l";
System.out.println("command for counting contigs "+command_to_count);
contigcount_p=Runtime.getRuntime().exec(command_to_count);
contigcount_p.wait();
由于正在使用管道符号,因此我无法成功执行命令。根据my的讨论,我已将变量包装在shell中:
Runtime.getRuntime().exec(新字符串[]{“sh”,“-c”,“grep\”>\“+filename+”| wc-l“})代码>
它在shell上执行命令时对我起作用,但当我尝试使用缓冲读取器读取其输出时:
BufferedReader reader =
new BufferedReader(new InputStreamReader(contigcount_p.getInputStream()));
String line=" ";
while((line=reader.readLine())!=null)
{
output.append(line+"\n");
}
它返回一个空值,我已经找到了一个临时解决方案,正如我在上一个问题上所讨论的:,但我想通过使用BufferedReader读取它的输出来使用正确的方法。当我使用您的{“sh”,“c”,“grep\”>“+filename+”\124; wc-l}
命令行时,它一直覆盖着我的文件
我不得不修改它,使引号是双引号,{“sh”、“-c”、“grep\“\”>\“\”“+filename+“|wc-l”}
所以,使用它作为我的测试文件的内容
>
>
>
Not a new line >
使用这个代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class TestProcess {
public static void main(String[] args) {
String filename = "test.tx";
String test = "grep \"\">\"\" "+filename+" | wc -l";
System.out.println(test);
try {
ProcessBuilder pb = new ProcessBuilder("sh", "-c", test);
pb.redirectError();
Process p = pb.start();
new Thread(new Consumer(p.getInputStream())).start();
int ec = p.waitFor();
System.out.println("ec: " + ec);
} catch (IOException | InterruptedException exp) {
exp.printStackTrace();
}
}
public static class Consumer implements Runnable {
private InputStream is;
public Consumer(InputStream is) {
this.is = is;
}
@Override
public void run() {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))){
String value = null;
while ((value = reader.readLine()) != null) {
System.out.println(value);
}
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
}
我能够产生这个输出
grep "">"" test.tx | wc -l
4
ec: 0
一般来说,在处理外部进程时,使用ProcessBuilder
通常比较容易,它有一些很好的选项,包括重定向错误/stdout和设置执行上下文目录…考虑改用ProcessBuilder。您能解释一下为什么我不能以这种方式获得输出吗?命令正在终端上成功执行。但是bufferedReader返回空值。ProcessBuilder为我工作:)但我想知道Runtime.exec()有什么问题?我怀疑这可能是我必须双转义引号的方式,但也可能是您读取输出流(或不读取错误流)的方式我没有双重转义引号。我并没有完全按照您的方式来做,我只是使用process builder而不是action.execute(),它工作得很好