PeakGen
PeakGen

Reputation: 23025

How to run a batch file inside Java package using Java code?

I need to run a batch file which is already inside of my Java package. Below is my code.

public class ScheduleTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {

       Process exec = Runtime.getRuntime().exec("test.bat");
    }

}

test.bat is located inside the scheduletest package, where the ScheduleTest class also located. Below is the package structure.

enter image description here

How can I make this happen?

EDIT

This is the content of my batch file

echo hello;
pause

Upvotes: 2

Views: 2345

Answers (2)

M A
M A

Reputation: 72854

Normally when your IDE compiles the sources, the test.bat should be placed in the folder that contains the binaries, preserving the same package structure, e.g. bin/scheduletest/test.bat. Assuming this, you can load the batch file using a classloader:

ClassLoader loader = ScheduleTest.class.getClassLoader();
URL resource = loader.getResource("scheduletest/test.bat");
Process exec = Runtime.getRuntime().exec(resource.getPath());

To read the output of the process, you'll need to get its input stream:

InputStream inputStream = exec.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while((line = br.readLine()) != null) {
    System.out.println(line);
}

However it's much better to have a resource directory for it, since automatic build procedures (e.g. Ant or Maven) would delete this file when cleaning.

Upvotes: 1

ktorn
ktorn

Reputation: 1052

Unless you really need to have your batch file in your java source code folder, I would just move it up to the root of your project, or better yet, create a /resources folder and put it there.

Then you can have the IDE or build system copy it to your bin/build. Your existing code can then run properly.

Upvotes: 1

Related Questions