可以使用java中的ProcessBuilder执行本地命令或脚本等工作:
以下是一个简单的使用java调用本地python脚本的例子。从某工程代码中整理出来的,未封装,仅供参考。
JAVA 代码:List<String> commands=new ArrayList();
commands.add("python");
commands.add(pkg);
commands.add("--ad=test");
//...其它参数添加
processBuilder.command(commands);
processBuilder.directory(path);//切换工作目录
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
StringBuilder result = new StringBuilder();
final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
try {
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
LOGGER.info(processBuilder.command().toString() + " --->: " + line);
}
} catch (IOException e) {
LOGGER.warn("failed to read output from process", e);
} finally {
IOUtils.closeQuietly(reader);
}
process.waitFor();
int exit = process.exitValue();
if (exit != 0) {
throw new IOException("failed to execute:" + processBuilder.command() + " with result:" + result);
} else {
return exit;
}
List<String> commands=new ArrayList();
commands.add("python");
commands.add(pkg);
commands.add("--ad=test");
//...其它参数添加
processBuilder.command(commands);
processBuilder.directory(path);//切换工作目录
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
StringBuilder result = new StringBuilder();
final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
try {
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
LOGGER.info(processBuilder.command().toString() + " --->: " + line);
}
} catch (IOException e) {
LOGGER.warn("failed to read output from process", e);
} finally {
IOUtils.closeQuietly(reader);
}
process.waitFor();
int exit = process.exitValue();
if (exit != 0) {
throw new IOException("failed to execute:" + processBuilder.command() + " with result:" + result);
} else {
return exit;
}
附:
在JavaSE5之前使用Runtime的exec方法执行本地命令.在JavaSE5之后,可以使用ProcessBuilder执行本地命令.
一篇不错的介绍ProcessBuilder的文章:
http://www.cnblogs.com/taven/archive/2011/12/17/2291460.html