项目需要,在java里调用一个c++ 二进制可执行文件,而且需要交互式调用,即需要动态地向可执行文件输入参数
具体实行功能:给可执行脚本提供input; 读取脚本执行结果。 google了很多帖子,发现一个好用的。稍稍做了改动。
public void encryLegacy(String password) {
String[] cmd = { legacyEncryTool, "-e", encryptAlgorith, saltString };
Process p;
try {
p = new ProcessBuilder(cmd).start();
// read erros
new Thread(() -> {
BufferedReader ir = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line = null;
try {
while ((line = ir.readLine()) != null) {
LOGGER.error("encrypted passwords '" + password + "' met error:" + line);
}
} catch (IOException e) {
LOGGER.error(e.getStackTrace().toString());
}
}).start();
// read data
new Thread(() -> {
BufferedReader ir = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
try {
while ((line = ir.readLine()) != null) {
retString = line;
writeResult(password + " " + line);//此行式将结果写入文件,不需要的可以注释掉
LOGGER.debug("password:" + password + " encryped:" + line);
}
} catch (IOException e) {
LOGGER.error(e.getStackTrace().toString());
}
}).start();
// read return code
new Thread(() -> {
int exitCode = 0;
try {
exitCode = p.waitFor();
System.out.println("++++++pw:" + retString);
} catch (InterruptedException e) {
e.printStackTrace();
LOGGER.error(e.getStackTrace().toString());
}
LOGGER.debug("Encryped passwords return code:" + exitCode);
}).start();
// final Scanner sc = new Scanner(System.in);
/*
* final Scanner sc = new Scanner("/root/dd"); final BufferedWriter bf = new
* BufferedWriter(new OutputStreamWriter(p.getOutputStream())); final String
* newLine = System.getProperty("line.separator"); while(true){ String c =
* sc.nextLine(); bf.write(c); bf.newLine(); bf.flush(); }
*/
final BufferedWriter bf = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
bf.write(password);
bf.newLine();
bf.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
疑惑的地方: 实例中用了多线程来分别获取inputStream, outputstream,waitforcode. 本来向从这个函数里把执行结果返回给调用函数的地方,可是取不到。发现主线程并没有等子线程退出就退出了。Java新手的我,只能先绕过去了,把结果写到文件里了。
欢迎大家留言解惑。