读书人

在java中调用外部程序的有关问题

发布时间: 2012-01-03 22:16:06 作者: rapoo

在java中调用外部程序的问题?
在java中调用一个“wc”命令,如下面的程序:
public class Test {

public static void main(String[] args) throws Exception{
String cmd = "wc Test.java > > a.txt ";
Runtime.getRuntime().exec(cmd);
}

}

无论怎么执行都看不到结果,这是在终端中的很简单的一条命令啊,谁知道这是怎么回事?谢!

[解决办法]
你把你的wc Test.java > > a.txt 这条命令拿到dos下面执行一下,,看能执行不..

他是找不到wc这个命令..所以报错啊..
[解决办法]
wc是什么命令?换一个可以在dos下识别的命令试试这种方法可以执行吗?
[解决办法]
这是我在工作写的一个程序,你可以参考一下:为了安全考虑,我把业务异常都改成了Exception,使用的时候用:
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;
}
}

读书人网 >J2SE开发

热点推荐