运行Java代码中一个.exe文件(Running a .exe file inside java

2019-10-18 07:13发布

我试图跑,我有一个Java代码中生成的.exe文件。 我用Java编写的,并使用MATLAB(其实际上是一个Simulink模型)生成.exe文件的GUI。 当我单独运行.exe文件(它也就是我双击),它会创建一个输出文件(这是我所期望的),但是当我跑我的Java代码它打开命令提示符,但它不会产生任何输出所有-in事实上,我甚至不能确定它是否运行我的.exe文件或没有。

这里是我的代码:

package combustionModel;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class GUIInterface extends JFrame {  
    JButton b1 = new JButton();

    public static void main(String[] args){
        GUIInterface gui = new GUIInterface();  
    }

    static class Action implements ActionListener{
        public void actionPerformed (ActionEvent e){
            JFrame frame2 = new JFrame();
            frame2.setVisible(true);
            frame2.setSize(100, 200);
            final JFileChooser fc  = new JFileChooser();
            fc.showOpenDialog(null);
            File file = fc.getSelectedFile();
            System.out.println(file.getAbsolutePath());
            try {
                Runtime runtime = Runtime.getRuntime();
                Process p = Runtime.getRuntime().exec("cmd /c start "+file.getAbsolutePath());
                p.waitFor();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }

    public GUIInterface(){
        setVisible (true);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400,200);
        setLayout(new FlowLayout());
        JPanel adpanel = new JPanel();
        JButton OK = new JButton();
        b1.addActionListener(new Action());
        adpanel.add(OK);
        adpanel.add(b1);
        super.add(adpanel);
    }

}

Answer 1:

通过将绝对路径试试

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


Answer 2:

 Process p = Runtime.getRuntime().exec("cmd /c "+file.getAbsolutePath());

试试这个代替

 Process p = Runtime.getRuntime().exec("cmd /c start "+file.getAbsolutePath());


文章来源: Running a .exe file inside java code