我必须从我的Java程序打开一个.exe文件。所以我先试着跟着代码走。
Process process = runtime.exec("c:\\program files\\test\\test.exe");
但是我得到了一些错误。然后我发现exe必须从c://program files/test/这个位置启动,然后它才会打开,没有错误。因此,我决定编写一个.bat文件并执行,这样它就可以cd到该位置并执行.exe文件。
以下是我的代码:
BufferedWriter fileOut;
String itsFileLocation = "c:\\program files\\test\\"
System.out.println(itsFileLocation);
try {
fileOut = new BufferedWriter(new FileWriter("C:\\test.bat"));
fileOut.write("cd\\"+"\n");
fileOut.write("cd "+ itsFileLocation +"\n");
fileOut.write("test.exe"+"\n");
fileOut.write("exit"+"\n");
fileOut.close(); // Close the output stream after all output is done.
} catch (IOException e1) {
e1.printStackTrace();
} // Create the Buffered Writer object to write to a file called filename.txt
Runtime runtime = Runtime.getRuntime();
try {
Process process =runtime.exec("cmd /c start C:\\test.bat");
} catch (IOException e) {
e.printStackTrace();
}
上面的代码运行得很好。但是,命令提示符也会在我的.exe (应用程序)的后面打开。它仅在.exe文件退出后关闭。
当我的应用统计时,我需要关闭我的命令提示符。
我的.bat文件在被程序写入后将如下所示。
cd\
cd C:\Program Files\test\
test.exe
exit
发布于 2012-05-21 21:16:29
您可以使用Runtime.exec(java.lang.String, java.lang.String[], java.io.File),您可以在其中设置工作目录。
或者,您可以使用ProcessBuilder,如下所示:
ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
pb.directory(new File("myDir"));
Process p = pb.start();
发布于 2015-08-25 20:27:19
运行文件的另一种方法如下:
import java.awt.Desktop;
import java.io.File;
public static void open(String targetFilePath) throws IOException
{
Desktop desktop = Desktop.getDesktop();
desktop.open(new File(targetFilePath));
}
发布于 2015-07-30 16:45:12
使用java通过命令行运行bat或任何其他程序的标准代码为:
runtimeProcess = Runtime.getRuntime().exec("cmd /c start cmd.exe /C\""+backup_path+"\"");
int processComplete = runtimeProcess.waitFor();
你可以使用分隔符继续多个文件,如:
https://stackoverflow.com/questions/10685893
复制相似问题