linux 执行 java 命令,在java中执行linux终端命令?

"本文探讨了Java代码中使用Runtime.exec()执行SOX命令时遇到的问题,重点在于如何解决'|'符号导致的壳执行概念理解错误。通过介绍使用Runtime.getRuntime().exec("/bin/sh", "-c", co)替代,解决了命令行管道符号的解析问题。"
摘要由CSDN通过智能技术生成

i'm trying to execute a SOX command from java, but unfortunately its returning an error everytime. Every other SOX commands are working perfectly though!!

Here is the code :

class Simple {

public static void main(String args[]) throws IOException, Exception {

Process p;

BufferedReader br;

String co = "sox speech_16.wav -p pad 0 2.5 | sox - -m speech_16.wav speech_output.wav";

p = Runtime.getRuntime().exec(co);

br = new BufferedReader(new InputStreamReader(p.getInputStream()));

int returnCode = p.waitFor();

System.out.println("reurn code : "+returnCode);

}

}

When I'm executing the same sox command in terminal, its working fine. I really can't understand what the problem is!! Is it because of the '|' symbol??

解决方案

The issue is that Runtime.exec() does not understand shell concepts such as "|". Instead try:

Runtime.getRuntime().exec("/bin/sh", "-c", co);

The problem is that exec runs a binary directly without invoking the shell. The "|" character is only recognized by the shell, not by sox. The "-c" tells the shell to run a single command, and passes the entire command as the single argument.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值