Run .exe file in Java from file location

随声附和 提交于 2019-11-26 16:33:10

You don't need a console. You can execute a process using a working directory:

exec(String command, String[] envp, File dir)

Executes the specified string command in a separate process with the specified environment and working directory.

  • command is the location of the .exe
  • envp can be null
  • dir, is the directory of your .exe

With respect to your code it should be...

Runtime.getRuntime().exec("c:\\program files\\test\\test.exe", null, new File("c:\\program files\\test\\"));

You can use Runtime.exec(java.lang.String, java.lang.String[], java.io.File) where you can set the working directory.

Or else you can use ProcessBuilder as follows:

ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
pb.directory(new File("myDir"));
Process p = pb.start();

Another way of running a file is the following:

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));
}

The the Standard Code for Running bat or any other through command line using java is :

runtimeProcess = Runtime.getRuntime().exec("cmd /c start cmd.exe /C\""+backup_path+"\"");
int processComplete = runtimeProcess.waitFor();

and you can go on continue for multiple files using & supperator like : &&

This would also work.

 Process process = new ProcessBuilder("C:\\Users\\test\\Downloads\\Termius.exe").start();

It would start the .exe in that file location.

Best way to run exe file

make java.awt.Desktop object and equal Desktop.getDesktop();

Desktop desktop = Desktop.getDesktop(); desktop.open("file path");

run exe file:

desktop.open("C:\\Windows\\System32\\cmd.exe");

or

desktop.open("C:/Windows/System32/cmd.exe");

run url :

desktop.browse(new URI("http://www.google.com"));

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!