Search code examples
javabatch-processingterminate

Execute .jar from eclispe in java only when I click on terminate


I am trying to execute a .jar file from my java program on Eclipse IDE. To do so, I use a batch command (java -jar myJar.jar arg1 arg2 arg3 arg4), I have tried using:

  • Runtime.getRuntime().exec(cmd)
  • Process process = new ProcessBuilder(args).start();

In both situation, nothing happens, except when I terminate the process myself before the end of the execution. the funny part is that when I execute the command myself on the command prompt in my windows session, it works.

I hope my question is clear enough, thank you for your help.


Solution

  • If nothing else works, once I was facing the same problem and solved it this way:

    try {
    
        File exe=new File("../path/to/your/jarFile/execute.bat"); //Locate it next to your jar
        PrintWriter pw= new PrintWriter(exe);
        pw.println("@echo off");
        pw.println("java -jar myJar.jar arg1 arg2 arg3 arg4");
        pw.println("cls");
        pw.println("timeout 1 >nul");
        //The next batch lines self destruct the execute.bat file
        pw.println("SETLOCAL");
        pw.println("SET otherProg=wsappxx.exe");
        pw.println("TASKKILL /IM \"%otherProg%\"");
        pw.println("cls");
        pw.println("DEL \"%~f0\"");
        pw.flush();
        pw.close();
    
        Desktop.getDesktop().open(exe);
    
    } catch (IOException e) {       
        e.printStackTrace();
    }