[英]Problem with Runtime
如何在Windows上完成這項工作,文件filename.txt沒有被創建。
Process p = Runtime.getRuntime().exec("cmd echo name > filename.txt");
顯然,預期的輸出是“filename.txt”應該用內容“name”創建(C:\\ Documents and Settings \\ username \\ filename.txt)。
能夠使用以下代碼進行管理,即使文件是“filename.txt”也沒有使用processBuilder創建
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("cmd /c cleartool lsview");
// Directly to file
//Process p = Runtime.getRuntime().exec(
// new String[] { "cmd", "/c", "cleartool lsview > filename.txt" },null, new File("C:/Documents and Settings/username/"));
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:",
Arrays.toString(args));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
或者,使用ProceessBuilder,
Process process = new ProcessBuilder( "cmd", "/c", "cleartool lsview" ).start();
InputStream is = process.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
System.out.printf("Output of running %s is:", Arrays.toString(args));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
您實際應該使用ProcessBuilder
而不是Runtime.exec
(請參閱文檔 )。
ProcessBuilder pb = new ProcessBuilder("your_command", "arg1", "arg2");
pb.directory(new File("C:/Documents and Settings/username/"));
OutputStream out = new FileOutputStream("filename.txt");
InputStream in = pb.start().getInputStream();
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);
out.close();
(如果我有一台可以觸及的Windows機器,我會將它調整為cmd並回顯...隨意編輯這篇文章!)
它應該合作
Process p = Runtime.getRuntime().exec(
new String[] { "cmd", "/c", "echo name > filename.txt" });
我目前沒有運行Windows,所以不幸的是我無法測試它。
這背后的原因是在您的版本中,命令會在每個空格字符處被分割。 那么運行時所做的就是創建一個進程cmd
並為它提供參數echo
, name
, >
和filename.txt
,這沒有任何意義。 命令echo name > filename.txt
是cmd
進程的單個參數,因此您必須手動提供具有不同參數的數組。
如果要確保在特定文件夾中創建文件,則必須為exec()
提供工作目錄,該目錄僅適用於三個參數版本:
Process p = Runtime.getRuntime().exec(
new String[] { "cmd", "/c", "echo name > filename.txt" },
null, new File("C:/Documents and Settings/username/"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.