[英]Going into a directory from Windows command prompt via Java
通過Java在Windows命令提示符下運行某些命令時遇到了一些麻煩。 我想進入我的system32文件夾並運行某個文件,但是該文件不會填充命令。 下面的代碼段:
System.out.print("Press 1 for Normal or 2 for Keygen - " + client);
String mode = input.nextLine().trim();
if (mode.equals("1")) {
String command = "cmd /c start cmd.exe";
final String dosCommand = "cmd /c dir /s";
final String location = "C:\\WINDOWS\\system32";
Process child = Runtime.getRuntime().exec(command);
OutputStream out = child.getOutputStream();
out.write(dosCommand.getBytes());
out.flush();
out.write(location.getBytes());
out.close();
} else if (mode.equals("2")) {
} else {
System.out.println("Option not recognised");
}
您似乎陷入了代碼困境。 嘗試使用此代替:
System.out.print("Press 1 for Normal or 2 for Keygen - " + client);
String mode = input.nextLine().trim();
if (mode.equals("1")) {
final String location = "C:\\WINDOWS\\system32";
Runtime rt = Runtime.getRuntime();
rt.exec("cmd.exe /c start dir /p", null, new File(location));
} else if (mode.equals("2")) {
} else {
System.out.println("Option not recognised");
}
這是我在自己的計算機上運行此代碼段時發生的情況:
如果要運行實際程序,則可以在對Runtime.exec()
的調用中指定它。 例如,假設您要啟動一個窗口並打印出Java版本。 此命令是java -version
,您可以使用以下代碼行:
rt.exec("cmd.exe /c start cmd /k java -version", null, new File(loc));
在這里,您會注意到我在命令中添加了一個額外的cmd /k
。 即使程序已完成運行,這也將使窗口保持打開狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.