0

I have made a java application that sometimes should call a batch file in order to move a video from a folder to another. The batch file is in the same directory of the main class of the project (ProjectName\src\move.bat).

I got the path of the batch file through the instruction:

String pathMoveBat = new java.io.File("src\\move.bat").getAbsolutePath();

and I use the code below (which is called by pressing a button in the application) to call that file:

Process move = Runtime.getRuntime().exec(pathMoveBat+" "+username+" "+dateFormat.format(currentDate)+" "+i+"");

Basically, when I click on the button nothing happen and seems that Windows cannot find the file move.bat.

Is there any other way to call that file from a jar?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Carlito
  • 166
  • 3
  • 7

1 Answers1

0

There are some points you need to understand before make it to work

  1. In order to execute a batch file you need an external program like command prompt(cmd).
  2. You need to know the location of batch file. Here in your case you are placing it under the src folder which will not available when you generate the jar. Since the src is a source folder so the batch should be copied to bin/dist/classes folder (output as per the IDE or project settings).
  3. While executing the process using Runtime make sure to provide relevant argument separated with spaces. Here you are passing username and current date and i.
  4. Once you have executed the batch file using Runtime.exec get the Process.getInputStream to catch the output if successfully executed. You will also need Process.getErrorStream to check if you have any error while executing the batch file.
  5. Last but not least close the streams, Process.getInputStream().close(); Process.getOutputStream().close(); Process.getErrorStream().close();

Runtime.getRuntime().exec("cmd /c move.bat "+username+" "+dateFormat.format(currentDate)+" "+i+"");

Switch to ProcessBuilder if you can, its better :https://stackoverflow.com/a/10723391/1129313

Community
  • 1
  • 1
Garry
  • 4,493
  • 3
  • 28
  • 48