我需要您在后续任务中的建议和指导。 我正在使用带有命令行实用程序的 libdmtx,它读取 ECC200 数据矩阵条码的图像文件,读取它们的内容,并将解码的消息写入标准输出。 我想在 linux 平台上的 java 程序中使用这个命令行实用程序。我正在使用 ubuntu linux。我已经在我的 linux 机器上安装了 libdmtx。当我调用命令时
dmtxread -n/home/admin/ab.tif
在linux终端上,它会立即给出图像中条形码的解码值。
当我要使用我的 java 程序调用此命令时,代码会在执行命令时出现问题,dotn 会给出输出。 看起来程序正在处理或挂起。
以下是调用以下命令的 java 代码
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
public class Classtest {
public static void getCodes(){
try
{
Process p;
String command[]=new String[3];
command[0]="dmtxread";
command[1]="-n";
command[2]="/home/admin/ab.tif";
System.out.println("Command : "+command[0]+command[1]+command[2]);
p=Runtime.getRuntime().exec(command); //I think hangs over here.
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line=reader.readLine();
if(line==null){
reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
line=reader.readLine();
System.out.print("Decoded :- "+line);
}else{
System.out.print("Error :- "+line);
}
System.out.println(p.waitFor());
}catch(IOException e1) {
e1.getMessage();
e1.printStackTrace();
}catch(InterruptedException e2) {
e2.getMessage();
e2.printStackTrace();
}
}
public static void main(String args[]){
getCodes();
}
}
请 friend 告诉我我的代码哪里出错了。
我引用了下面的文章,但没有得到任何帮助
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=1
请各位 friend 指教! 谢谢!
这是我在其中使用 ProcessBuilder 类的新代码,该代码也提供与上面代码相同的输出,它卡在行 进程process = pb.start();
public class Test {
public static void main(final String[] args) throws IOException, InterruptedException {
//Build command
List<String> commands = new ArrayList<String>();
commands.add("dmtxread");
commands.add("-n");
commands.add("/home/admin/ab.tif");
System.out.println(commands);
//Run macro on target
ProcessBuilder pb = new ProcessBuilder(commands);
pb.redirectErrorStream(true);
Process process = pb.start();
//Read output
StringBuilder out = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null, previous = null;
while ((line = br.readLine()) != null){
System.out.println(line);
}
//Check result
if (process.waitFor() == 0)
System.out.println("Success!");
System.exit(0);
//Abnormal termination: Log command parameters and output and throw ExecutionException
System.err.println(commands);
System.err.println(out.toString());
System.exit(1);
}
请指导我解决这个问题。 谢谢你!
最佳答案
readLine 会阻塞,直到它从错误流中接收到新的一行。因此,如果没有输出,您的程序将无法通过第一个 readLine。
为简单起见,我建议您使用 ProcessBuilder
而不是 Runtime.exec()
,这样您就可以按如下方式合并两个 InputStreams:
ProcessBuilder builder = new ProcessBuilder(cmd,arg0,arg1);
builder.redirectErrorStream(true);
Process process = builder.start();
所以,现在您可以只读一个。
或者,您可以使用单独的线程来使用两个 InputStreams。
希望对你有帮助
关于java - 为什么命令行实用程序在通过 java 程序调用时挂起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10515168/