[英]Problem with the output of a cmd command in java
我試圖讀取cmd命令的結果(例如dir)。 創建進程后,我將BufferedReader
與InputStreamReader
結合使用。 出於某種原因,即使我知道必須要讀取一些輸出, BufferedReader
也會一直空着。
這是我正在使用的代碼:
String[] str = new String[] {"cmd.exe", "/c",
"cd", "c:\\",
"dir", "/b", "/s"
};
Runtime rt = Runtime.getRuntime();
try{
Process p = rt.exec(str);
InputStream is =p.getInputStream();
System.out.println(is.available());
InputStreamReader in = new InputStreamReader(is);
StringBuffer sb = new StringBuffer();
BufferedReader buff = new BufferedReader(in);
String line = buff.readLine();
System.out.println(line);
while( line != null )
{
sb.append(line + "\n");
System.out.println(line);
line = buff.readLine();
}
System.out.println( sb );
if ( sb.length() != 0 ){
File f = new File("test.txt");
FileOutputStream fos = new FileOutputStream(f);
fos.write(sb.toString().getBytes());
fos.close();
}
}catch( Exception ex )
{
ex.printStackTrace();
}
你有:
String[] str = new String[] {"cmd.exe", "/c",
"cd", "c:\\",
"dir", "/b", "/s"
};
這似乎對我不對。 您不能在一個命令行上將多個命令放到cmd.exe中。 那是一個批處理文件。
嘗試擺脫cd或dir的所有內容。
編輯:確實:
C:\>cmd.exe /c cd c:\ dir
The system cannot find the path specified.
可能有錯誤。 在這種情況下,您還應該捕獲getErrorStream()
您運行的命令是cmd.exe /c cd c:\\ dir /b /s
。 我認為這不符合你的期望。
我的意思是你將兩個命令連接成一行,而Windows shell可能不喜歡這樣。 嘗試類似的東西
String[] str = new String[] {"cmd.exe", "/c",
"cd", "c:\\", "&&",
"dir", "/b", "/s"
};
&&
將告訴shell執行cd c:\\
然后在第一個命令成功時執行dir /b /s
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.