How to Run a Batch File from Java Code onclicking a Button - java

On clicking a button in a jsp page, I want to run a batch file. I wrote this code to execute a batch file inside a method, but it's not working. Plz help me out.
public String scheduler() {
String result=SUCCESS;
try {
Process p = Runtime.getRuntime().exec("cmd /c start.bat", null, new File("C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\start"));
System.out.println("manual scheduler for application.."+p);
} catch(Exception e) {
}
}

Add this code,
batFile.setExecutable(true);
//Running bat file
Process exec = Runtime.getRuntime().exec(PATH_OF_PARENT_FOLDER_OF_BAT_SCRIPT_FILE+File.separator+batFile.getName());
byte []buf = new byte[300];
InputStream errorStream = exec.getErrorStream();
errorStream.read(buf);
logger.debug(new String(buf));
int waitFor = exec.waitFor();
if(waitFor==0) {
System.out.println("BAT script executed properly");
}

According to this, the following code should work (just remove the cmd /c):
public String scheduler() {
String result=SUCCESS;
try {
File f = new File("C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\start")
Process p = Runtime.getRuntime().exec("start.bat", null, f);
System.out.println("manual scheduler for application.."+p);
} catch(Exception e) {
}
}

It's not clear here whether you just want to run a bat file or you want to wait for it to run.
// the location where bat file is located is required eg. K:/MyPath/MyBat.bat in my case
// If bat file is in classpath then you can provide direct bat file name MyBat.bat
**Runtime rt = Runtime.getRuntime() ;
Process batRunningProcess= rt.exec("cmd /c K:/MyPath/MyBat.bat");**
// This is to wait for process to complete
//if process is completed then value will be 0
**final int exitVal = lawTab_Indexer.waitFor();**
// This line is not required if you just want to run a bat file and dont want to wait for it to get completed.

Related

Command prompt is not closing after completing even after writing exit

I have following java code
public static void main(String a[]) {
String location = "C:\\Users\\test\\output\\testProject";
File dir = new File("C:\\Users\\test\\cmds");
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "Start /wait","packageProject.bat",location);
pb.directory(dir);
Process p = null;
try {
p = pb.start();
p.waitFor();
}
catch (IOException e) {
e.printStackTrace();
}
catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("Folder created");
}
Batch file is
cd "C:\Users\test\output\test-master"
mvn clean install -DskipTests
exit
It is packaging file but not command prompt is not closing once process is complete.
Please suggest.
You should remove wrapper CMD.EXE and start, just call the batch file directly as:
String bat = new File(dir, "packageProject.bat").getAbsolutePath();
ProcessBuilder pb = new ProcessBuilder(bat , location);
pb.directory(dir);
Process p = pb.start();
p.waitFor();
If this process generates a lot of output you may run into a second problem if you don't consume error and output streams. You can do this in background threads, or simply send stdout/err to files by adding these calls before pb.start():
pb.redirectOutput(new File(location, "std.out"));
pb.redirectError(new File(location, "std.err"));

I've already created a Process Builder. How do I run all of the programs in the Process builder?

Heere is the code I have so far. How do I have miktex-pdftex run?
List<String> processes = new ArrayList<String>();
processes.add("miktex-pdftex --output-directory=[Directory] [file_name].tex");
ProcessBuilder processbuild = new ProcessBuilder(processes);
First, you need to make sure the command you are using actually works at the command. If it does not, then it's not going to work in Java.
Next, one of the main reasons for using ProcessBuilder is to deals with spaces in the command/parameters better then Runtime#exec.
String command = "/Applications/MiKTeX Console.app/Contents/bin/miktex-pdftex";
String outputDir = System.getProperty("user.dir");
String sourceFile = "Sample.tex";
List<String> commands = new ArrayList<>();
commands.add(command);
commands.add("--interaction=nonstopmode");
commands.add("--output-directory=" + outputDir);
commands.add(sourceFile);
So the above is very simple...
The command I want to run is /Applications/MiKTeX Console.app/Contents/bin/miktex-pdftex (I'm running on MacOS and I couldn't get the command installed outside the application bundle)
I want the output-directory to be the same as the current working directory (System.getProperty("user.dir")), but you could supply what every you need
I'm running in "nonstopmode" (--interaction=nonstopmode) because otherwise I would be required to provide input, which is just more complex
And my input file (Sample.tex) which is also in the working directory.
Next, we build the ProcessBuilder and redirect the error stream into the InputStream, this just reduces the next to read these two streams separately...
ProcessBuilder pb = new ProcessBuilder(commands);
pb.redirectErrorStream(true);
Next, we run the command, read the contents of the InputStream (otherwise you can stall the process), you can do what ever you want with this, I've just echoed it to the screen
try {
Process process = pb.start();
InputStream is = process.getInputStream();
int in = -1;
while ((in = is.read()) != -1) {
System.out.print((char)in);
}
int exitValue = process.waitFor();
System.out.println("");
System.out.println("Did exit with " + exitValue);
} catch (IOException | InterruptedException ex) {
ex.printStackTrace();
}
The use int exitValue = process.waitFor(); here is just to ensure that command has completed and get the exit value it generated. Normally, 0 is success, but you'd need to read the documentation of the command to be sure

Best way to run a batch (shell / CMD) command in Java / Eclipse?

I have created the following code below in Eclipse / java which executes a batch file, which in turn should also execute once all my TestNG tests have executed but sometimes the bat file will execute and sometimes it dosnt do anything at all, any ideas?
#AfterSuite(alwaysRun = true)
public void executeBatFile() {
try {
List cmdAndArgs = Arrays.asList("cmd", "/c", "copyPasteImgs.bat");
File dir = new File(Paths.get(System.getProperty("user.dir") + "/..").toRealPath() + "\\");
ProcessBuilder pb = new ProcessBuilder(cmdAndArgs);
pb.directory(dir);
Process p = pb.start();
} catch (IOException e) {
e.printStackTrace();
}
}
The batch files moves files from a local folder to a remote folder (When the batch file hasnt worked via eclipse or invoked via jenkins I have manually executed the batch file and it did its jobs, very weird...)
thanks for your help
Apache Commons CLI provides functionalities to handle using command line from java. You can also use the exit value to have an idea about what is going on with your command. For example:
String command = "dir";
CommandLine oCmdLine = CommandLine.parse(command);
DefaultExecutor oDefaultExecutor = new DefaultExecutor();
oDefaultExecutor.setExitValue(0);
try {
int iExitValue = oDefaultExecutor.execute(oCmdLine);
} catch (ExecuteException e) {
System.err.println("Execution failed.");
e.printStackTrace();
} catch (IOException e) {
System.err.println("permission denied.");
e.printStackTrace();
}

Running a .BAT file in JAVA without opening a command prompt

I've been trying to run an executable .bat file in Java using the line:
Runtime.getRuntime().exec("call " + batFile);
But it returns an error
Could not start process with commandLine nullCreateProcess: call batfilename here error=2
IOException: Create Process: call batfilename here error=2
I managed to bypass this by replacing the String in the exec() function with "cmd /c start " + batFile but this opens a command prompt which is not allowed.
Are there workarounds to this? Thanks!
Try running the batch file directly, for example...
ProcessBuilder pb = new ProcessBuilder("C:/Test.bat");
pb.redirectError();
try {
Process p = pb.start();
try (InputStream inputStream = p.getInputStream()) {
int in = -1;
while ((in = inputStream.read()) != -1) {
System.out.print((char)in);
}
}
System.out.println("Exited with " + p.waitFor());
} catch (IOException | InterruptedException ex) {
ex.printStackTrace();
}
This was the batch file...
#echo Hello World
(I know, massive) and the code outputted...
Hello World
Exited with 0
A little late but for others who want to try I found the /B of start command.
String[] command = { "cmd", "/C", "start", "/B", "test.bat" };
File path = new File("C:/Users/Me/Desktop/dir/");
Runtime.getRuntime().exec(command, null, path);

java variable linked to batch file

I am currently learning java and I encountered this problem. I am not sure if it can be done like this as I am still in the learning stage. So in my java main coding:
import java.io.File;
import java.io.IOException;
public class TestRun1
{
public static void main(String args[])
{
//Detect usb drive letter
drive d = new drive();
System.out.println(d.detectDrive());
//Check for .raw files in the drive (e.g. E:\)
MainEntry m = new MainEntry();
m.walkin(new File(d.detectDrive()));
try
{
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("cmd /c start d.detectDrive()\\MyBatchFile.bat");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
The "cmd /c start d.detectDrive()\MyBatchFile.bat" does not work. I do not know how to replace the variable.
And i created a batch file (MyBatchFile.bat):
#echo off
set Path1 = d.detectDrive()
Path1
pause
set Path2 = m.walkin(new File(d.detectDrive()))
vol231.exe -f Path2 imageinfo > Volatility.txt
pause
exit
It does not work. Please do not laugh.
I really isn't good in programming since I just started on java and batch file. Can anyone help me with it? I don't want to hard code it to become a E: or something like that. I want to make it flexible. But I have no idea how to do it. I sincerely ask for any help.
Procedure:
You should append the return value of the method which detects the drive, to the filename and compose the proper Batch command string.
Steps:
Get the return value of the method
String drive = d.detectDrive();
so, drive contains the value E:
append the value of drive to the filename
drive+"\MyBatchFile.bat"
so, we have E:\MyBatchFile.bat
append the result the batch command
cmd /c start "+drive+"\MyBatchFile.bat
result is cmd /c start E:\MyBatchFile.bat
So to invoke the batch command, the final code should be as follows:
try {
System.out.println(d.detectDrive());
Runtime rt = Runtime.getRuntime();
String drive = d.detectDrive();
// <<---append the return value to the compose Batch command string--->>
Process p = rt.exec("cmd /c start "+drive+"\\MyBatchFile.bat");
}
catch (IOException e) {
e.printStackTrace();
}

Categories

Resources