我試圖使用cmd.exe來搜索特定目錄中的文件,然後在java程序中顯示路徑並將其寫入文件。問題是這個過程永遠不會終止。Java中的CMD.exe命令沒有終止
這裏是我的代碼:
String[] str = new String[] { "cmd.exe ", "cd c:\\",
" dir /b /s documents", "2>&1" };
Runtime rt = Runtime.getRuntime();
try{
Process p = rt.exec(str);
InputStream is =p.getInputStream();
InputStreamReader in = new InputStreamReader(is);
StringBuffer sb = new StringBuffer();
BufferedReader buff = new BufferedReader(in);
String line = buff.readLine();
while(line != null)
{
sb.append(line + "\n");
line = buff.readLine();
}
System.out.println(sb);
File f = new File("test.txt");
FileOutputStream fos = new FileOutputStream(f);
fos.write(sb.toString().getBytes());
fos.close();
}catch(Exception ex)
{
ex.printStackTrace();
}
我應該把cmd/c而不是cmd.exe作爲命令在str中?如果是這樣,我試過了,並得到一個IOException - 系統找不到指定的文件。 – chama 2010-02-04 15:15:10
你必須把'/ c'放在一個單獨的參數中。 Runtime.exec(「cmd.exe」,「/ c」,...) – tangens 2010-02-04 15:29:08
帶參數/ c的cmd.exe,以便您的代碼讀取:String [] str = new String [] {「cmd.exe」, 「/ c」,「\」cd c:\\ && dir/b/s documents \「」};'這是否工作我不能說,但那將是tangens的意思:)請注意,多個命令需要用'&&'分隔,並用「」括起來。 – 2010-02-04 15:35:25