从文件位置运行Java中的.exe文件

时间:2012-05-21 13:10:22

标签: java windows batch-file exe bufferedreader

我必须从我的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

6 个答案:

答案 0 :(得分:17)

您不需要控制台。您可以使用工作目录执行进程:

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

在单独的进程中执行指定的字符串命令 使用指定的环境和工作目录。

  • 命令是.exe
  • 的位置
  • envp可以为null
  • dir,是.exe
  • 的目录

关于你的代码应该是......

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

答案 1 :(得分:10)

您可以使用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();

答案 2 :(得分:6)

运行文件的另一种方法如下:

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

答案 3 :(得分:3)

使用java运行bat或任何其他命令行的标准代码是:

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

你可以继续使用& supperator喜欢:&&

答案 4 :(得分:1)

这也可以。

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

它将在该文件位置启动.exe。

答案 5 :(得分:0)

运行exe文件的最佳方式

制作java.awt.Desktop对象并等于Desktop.getDesktop();

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

运行exe文件:

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

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

运行网址:

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