我试图使用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