在java中调用一个“wc”命令,如下面的程序:
public class Test {
public static void main(String[] args) throws Exception{
String cmd = "wc Test.java >>a.txt";
Runtime.getRuntime().exec(cmd);
}
}无论怎么执行都看不到结果,这是在终端中的很简单的一条命令啊,谁知道这是怎么回事?谢!
public class Test {
public static void main(String[] args) throws Exception{
String cmd = "wc Test.java >>a.txt";
Runtime.getRuntime().exec(cmd);
}
}无论怎么执行都看不到结果,这是在终端中的很简单的一条命令啊,谁知道这是怎么回事?谢!
Cmd cmd = new Cmd("commandLine");
cmd.execWait();以下是原码:
public class Cmd extends Thread { /** [baseName] 共通設定 */
public static final int SLEEP_TIME = 2000;
/** 戻り値(正常終了) */
public static final int RETURN_OK = 0;
/** 戻り値(正常終了) */
public static final int RETURN_NG = -1; /** コマンド文字列の宣言 */
private String com;
/** 戻り値の宣言 */
private static int exitValue;
/**
* コンストラクタ
*/
public Cmd() {
} /**
* コンストラクタ(パラメータあり)
* @param command コマンド文字列
* @throws Exception 例外
*/
public Cmd(final String command) throws Exception {
this.com = command;
this.setExitValue(RETURN_OK);
} /**
* 外部コマンド実行。<br>
* @param cmdStr 外部コマンド外部コマンド
* @return int コマンド実行結果 0:正常終了、-1:I/O例外、0、-1以外:コマンドの戻値(正常以外)
* @throws Exception 外部コマンドが常終了しなかった場合
*/
public final int exec(final String cmdStr) throws Exception {
try {
if (cmdStr == null) {
return -1;
}
start();
Thread.sleep(SLEEP_TIME);
} catch (Exception e) {
throw new Exception("コマンドを実行することができませんでした.\n");
} return getExitValue();
}
/**
* 外部コマンド実行WaitResult。<br>
* @param cmdStr 外部コマンド外部コマンド
* @return int コマンド実行結果 0:正常終了、-1:I/O例外、0、-1以外:コマンドの戻値(正常以外)
* @throws Exception 外部コマンドが常終了しなかった場合
*/
public final int execWait() throws Exception {
try {
start(); join();
} catch (Exception e) {
Logger.debug(getClass().getName(), "execWait", e);
throw new Exception("コマンドを実行することができませんでした.\n");
} return getExitValue();
} /**
* 外部コマンド実行。<br>
*/
public final void run() {
DataInputStream in = null;
BufferedReader d = null;
try {
String line;
Runtime runTime = Runtime.getRuntime();
Process ps = runTime.exec(com);
ps.waitFor();
in = new DataInputStream(ps.getInputStream());
d = new BufferedReader(new InputStreamReader(in));
while ((line = d.readLine()) != null) {
Logger.debug(getClass().getName(), line);
}
setExitValue(ps.exitValue());
} catch (IOException e) {
this.setExitValue(RETURN_NG);
} catch (InterruptedException e1) {
this.setExitValue(RETURN_NG);
} finally {
if (d != null) {
try {
d.close();
} catch (IOException e2) {
// 処理続行
}
}
if (in != null) {
try {
in.close();
} catch (IOException e3) {
// 処理続行
}
}
}
} /**
* @return int ステータス
*/
private int getExitValue() {
return exitValue;
} /**
* @param i 戻り値
*/
private void setExitValue(final int i) {
exitValue = i;
}
}