【发布时间】:2016-10-18 23:05:08
【问题描述】:
我有几个需要用 Java 程序运行的命令:
> db2cmd -i "db2 -tvsf \"C:\file1.sql\""
> db2cmd -i "db2 -tvsf \"C:\file2.sql\""
我每个人都创建了一个新线程,但线程永远不会结束。 db2cmd 打开一个新的命令提示符,您可以在其中输入 db2 命令。但是official IBM documentation 表示您可以使用 -i 标志在同一个命令窗口上运行它。
public class DirectoryRunner {
public static void main(String[] args){
File f = new File("file1.sql");
String cmd = "db2cmd -i \"db2 -tvsf \\\"" + f.getAbsolutePath() + "\\\"\""
try {
Process p = Runtime.getRuntime().exec(cmd);
IOThreadHandler outputHandler = new IOThreadHandler(
p.getInputStream());
outputHandler.start();
p.waitFor();
System.out.println(outputHandler.getOutput());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
private static class IOThreadHandler extends Thread {
private InputStream inputStream;
private StringBuilder output = new StringBuilder();
IOThreadHandler(InputStream inputStream) {
this.inputStream = inputStream;
}
public void run() {
Scanner br = null;
try {
br = new Scanner(new InputStreamReader(inputStream));
String line = null;
while (br.hasNextLine()) {
line = br.nextLine();
output.append(line + System.getProperty("line.separator"));
}
} finally {
br.close();
}
}
public StringBuilder getOutput() {
return output;
}
}
}
【问题讨论】:
-
您可以用
new ProcessBuilder("db2cmd", "-i, "db2 -tvsf \"" + f.getAbsolutePath() + "\"").inheritIO().start().waitFor()替换所有代码。这将允许您查看命令的输出及其标准错误,这可能是在告诉您找不到文件,因为其路径中的反斜杠没有像双引号 (") 那样转义。 -
您为什么要在应用程序内部通过 JDBC 直接运行 SQL 而不是输出命令?
标签: java db2 command-line-arguments db2-luw