Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a batch file from java?

I want to execute a batch file from a java program.

I am using the following command.

Runtime.getRuntime().exec("server.bat");

But the problem is I want to give a reative path instead of absolute path so that I can deploy that java project on any comp.

The dir structure of the project is like as follows:

com
   |
  project
   |
   ------ parser
   |         |_____ Main.java
   |
   -------util
             |_____ Server.bat

I want to run the "Server.bat" file in the "util" dir from the "Main.java" file in the "parser" dir.

like image 418
Yatendra Avatar asked Sep 14 '09 12:09

Yatendra


People also ask

What is batch file in Java?

It consists of a series of commands to be executed by the command-line interpreter, stored in a plain text file. A batch file may contain any command the interpreter accepts interactively and use constructs that enable conditional branching and looping within the batch file, such as IF , FOR , and GOTO labels.

How do I run a batch file in spring boot?

We need to add the @EnableBatchProcessing annotation in the configuration class file. The @EnableBatchProcessing annotation is used to enable the batch operations for your Spring Boot application. The reader() method is used to read the data from the CSV file and writer() method is used to write a data into the SQL.


1 Answers

When Java is running and you use Runtime.exec() with a relative path, relative means relative to the current user direcory, where the JVM was invoked.

This may work

Runtime.getRuntime().exec("cmd.exe", "/c", "./com/projct/util/server.bat");

if you start java from com's parent directory.

Or you must calculate an absolut path:

Runtime.getRuntime().exec("cmd.exe", "/c", 
System.getProperty("user.dir")+"/com/projct/util/server.bat");

I forget, read When Runtime.exec() won't.

like image 75
PeterMmm Avatar answered Oct 10 '22 00:10

PeterMmm