Mehdi
Mehdi

Reputation: 21

Running a .exe file inside java code

I am trying to run a .exe file that I have generated inside a Java code. I have a GUI written in Java and the .exe file is generated using MATLAB (its actually a Simulink model). When I run the .exe file separately (i.e. I double click on it) it will create an output file ( which is what I expect) but when I run my Java code it opens the command prompt but it won't generate any outputs at all -in fact I am not even sure if it runs my .exe file or not.

Here is my code:

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

}

Upvotes: 1

Views: 11811

Answers (2)

shreyansh jogi
shreyansh jogi

Reputation: 2102

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

try this instead

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

Upvotes: 1

John
John

Reputation: 281

Try by passing the absolute path

example

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

Upvotes: 1

Related Questions