[英]Run bat file from different disk with java
我試圖從 C:/abc/def/coolBat.bat 運行一個 bat,但我的 java 工作區在 D:/
我試過:
String cmd = "cmd /c /start C:/abc/def/coolBat.bat";
Runtime.getRuntime().exec(cmd);
但是沒有用,所以我嘗試了這個
String[] command = { "cmd.exe", "/C", "C:/abc/def/coolBat.bat" };
Runtime.getRuntime().exec(cmd);
也沒有用。 也試過這個
Executor exec = new DefaultExecutor();
exec.setWorkingDirectory(new File("C:/abc/def"));
CommandLine cl = new CommandLine("coolBat.bat");
int exitvalue = exec.execute(cl);
說找不到文件。
也嘗試過這樣的事情:
Runtime.getRuntime().exec("cmd cd /d C:/abc/def/ && coolBat.bat");
沒事了。 奇怪的是這個命令:
cd /d C:/abc/def/ && coolBat.bat
當我在 cmd 中執行時有效。 值得一提的是,bat文件將一些文件復制到另一個目錄,全部在C:/
已編輯 N°1
CD C:\abc\def\MN
copy almn + ctmn + bamn C:\abc\def\mn_sf.txt
CD C:\abc\def\ME
copy alme + ctme + bame C:\abc\def\me_sf.txt
CD C:\abc\def\
if exist MN.txt del MN.txt
if exist ME.txt del ME.txt
if exist JUZ.txt del JUZ.txt
if exist FUNC.txt del FUNC.txt
if exist AHO.txt del AHO.txt
CD C:\
允許 MS Windows 使用關聯的應用程序運行您的批處理文件(或任何其他應用程序):
所需的進口:
import java.awt.Desktop;
這是您可以嘗試的代碼:
String filePath = "C:/abc/def/coolBat.bat";
if (Desktop.isDesktopSupported()) {
try {
File myFile = new File(filePath);
Desktop.getDesktop().open(myFile);
}
catch (IOException | IllegalArgumentException ex) {
System.err.println("Either there is no application found "
+ "which is associatd with\nthe file you want to work with or the "
+ "file doesn't exist!\n\n" + filePath);
}
}
Java 版本可以作為:
String[] command = {"cmd.exe", "/C", "Start", "/D", "c:\\abc\\def", "c:\\abc\\def\\coolBat.bat"};
Process process = Runtime.getRuntime().exec(command);
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((line = errReader.readLine()) != null) {
System.out.println(line);
}
System.out.flush();
int retCode = process.waitFor();
System.out.println("Return code: " + retCode);
好吧,我終於讓它工作了,只需將我的工作區更改為 C:/
顯然問題是它無法從 D:/ 更改為 C:/ 以執行。 我運行了我之前嘗試過的相同命令,沒有問題。
猜猜問題仍然存在,為什么從 Java 運行命令時它不能從 D:/ 更改為 C:/。
感謝大家的幫助
嘗試這個:
String[] command = { "cmd.exe", "/C", "C: && C:/abc/def/coolBat.bat" };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.