我需要从 Java 调用 Unix 命令。代码如下。
String strCmd = "iconv -f "+ strSrcEncoding+" -t "+ strTgtEncoding + " <<< "+"\""+InputMessage+"\"";
String commands[] = {"bash","-c",strCmd};
Process proc = Runtime.getRuntime().exec(commands);
String strData = null;
// Get the error Stream
BufferedReader brStdError = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
StringBuilder sbError = new StringBuilder();
// read any errors from the attempted command
while ((strData = brStdError.readLine()) != null) {
sbError.append(strData);
}
if(sbError.toString().isEmpty())
return "success";
else
return "failure"+sbError.toString();
当我传递大量数据时出现错误
"bash": java.io.IOException: error=7, Argument list too long
我尝试使用 echo 代替,如下所示
echo <<InputMessage>> | iconv -f utf8 -t Cp930
但是出现了同样的错误
我错过了什么吗?
最佳答案
可以在命令行上传递给程序的数据量是有限的。如果您有大量数据,您应该使用其标准输入流将其传递给 iconv,即将其写入 proc.getOutputStream
。这是一个例子:
OutputStream os = proc.getOutputStream();
os.write(InputMessage.getBytes(strSrcEncoding));
os.close();
不幸的是,对于较长的消息,这也会失败,因为 iconv
将填充它所连接的管道的缓冲区,并等待管道被读取。解决方案是从一个线程向 iconv
写入数据,然后从另一个线程读取输出。由于所有这些陷阱,处理外部进程是一件麻烦事。您可以在这里阅读更多相关信息:http://www.javaworld.com/jw-12-2000/jw-1229-traps.html Apache commons exec帮助您处理其中的一些问题。
另一方面,您为什么要使用 iconv?您知道 Java 对大多数字符编码有良好的库支持,包括 cp930
吗?
关于java - IOException : error=7, 命令行参数列表太长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16912103/