2

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I would not put it directly in the binaries of the IDE as you may find that cleaning your project will automatically delete your batch file too. What you want is for the IDE or build system to copy it to the bin as part of the building process.
Thanks. It worked. However it is not showing any batch file to me. It happened even I gave it the complete batch file path. I have updated my question with the content of batch file.
@JustCause You're not reading from the output stream of the process. See my updated answer.
Yiu are the best. Thanks.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.