Dil*_*mar 18 java windows exe batch-file bufferedreader
我必须从我的Java程序中打开一个.exe文件.所以我尝试了第一个代码.
Process process = runtime.exec("c:\\program files\\test\\test.exe");
Run Code Online (Sandbox Code Playgroud)
但是我收到了一些错误.然后我发现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();
}
Run Code Online (Sandbox Code Playgroud)
上面的代码完美无缺.但是,命令提示符也会在我的.exe(应用程序)后面打开.它仅在.exe文件退出后关闭..
当我的应用程序统计信息时,我需要克隆我的命令提示符.
程序编写后,我的.bat文件就像是跟随文件.
cd\
cd C:\Program Files\test\
test.exe
exit
Run Code Online (Sandbox Code Playgroud)
Sch*_*fty 19
您不需要控制台.您可以使用工作目录执行进程:
exec(String命令,String [] envp,文件目录)
在具有指定环境和工作目录的单独进程中执行指定的字符串命令.
关于你的代码应该是......
Runtime.getRuntime().exec("c:\\program files\\test\\test.exe", null, new File("c:\\program files\\test\\"));
Run Code Online (Sandbox Code Playgroud)
Kul*_*ain 11
您可以使用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();
Run Code Online (Sandbox Code Playgroud)
另一种运行文件的方法如下:
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));
}
Run Code Online (Sandbox Code Playgroud)
使用java通过命令行运行bat或任何其他的标准代码是:
runtimeProcess = Runtime.getRuntime().exec("cmd /c start cmd.exe /C\""+backup_path+"\"");
int processComplete = runtimeProcess.waitFor();
Run Code Online (Sandbox Code Playgroud)
您可以使用 & 分隔符继续处理多个文件,例如:&&
| 归档时间: |
|
| 查看次数: |
79851 次 |
| 最近记录: |