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

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);

Related

run cmd command as administrator through java program

I need to build a java program to reset network in windows 10, this command needs cmd to be opened as administrator I tried to build it, but it gives me this error
Cannot run program "runas /profile /user:Administrator "cmd.exe /c Powrprof.dll,SetSuspendState"": CreateProcess error=2, The system cannot find the file specified
this is my code
try {
String[] command
= {
"runas /profile /user:Administrator \"cmd.exe /c Powrprof.dll,SetSuspendState\"",};
Process p = Runtime.getRuntime().exec(command);
new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
PrintWriter stdin = new PrintWriter(p.getOutputStream());
stdin.println("netsh winsock reset");
stdin.close();
int returnCode = p.waitFor();
System.out.println("Return code = " + returnCode);
stat_lbl.setText("Network reset Successfully");
} catch (IOException | InterruptedException e) {
System.out.println(e.getMessage());
}
I don't understand what the problem is and how can I resolve it
You're giving the command as an array with a single element, which is treated as a single command. You're already giving the command as an array - split it accordingly, where runas is the command, and everything else is an argument to runas:
String[] command = {
"runas",
"/profile",
"/user:Administrator",
"cmd.exe /c Powrprof.dll,SetSuspendState",
};
Note that you don't have to add quotes to the last argument.
You can make your program a bit better by using ProcessBuilder. Now you're redirecting streams yourself, but you can easily let ProcessBuilder handle that for you:
Process p = new ProcessBuilder(command).inheritIO().start();
PrintWriter stdin = new PrintWriter(p.getOutputStream());
stdin.println("netsh winsock reset");
stdin.close();
int returnCode = p.waitFor();
System.out.println("Return code = " + returnCode);

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"));

Why will Java not open up a Batch file when executed with a ProcessBuilder?

I've coded a Java program to open up a Batch file that is imported into the resources of the program.
Even by running my code in Eclipse, the Batch file does not work. I have opened the Batch file using the Project Explorer, so the Batch file works.
The file serves, essentially, as a Command Prompt, for when it may be blocked by Group Policies.
The contents of the Batch file are as follows...
#ECHO OFF
TITLE Command Prompt
VER | FIND /I " "
ECHO A portable CMD made with Batch.
ECHO.
CD /D %SYSTEMDRIVE% && CD %USERPROFILE%
:USER
SET /P INPUT="%CD%>"
%INPUT%
ECHO.
GOTO USER
Now, when I execute this code:
ClassLoader classLoad = this.getClass().getClassLoader();
URL batchPath = classLoad.getResource("cmd.bat");
String batch = batchPath.toString();
System.out.println("batchPath " + batchPath);
System.out.println("batch " + batch);
String batchCommand = batch.replaceFirst("file:/", "");
batchCommand = batchCommand.replace('/', '\\');
batchCommand = batchCommand.replaceAll("%20", " ");
System.out.println(batchCommand);
ProcessBuilder pb = new ProcessBuilder("\"" + batchCommand + "\"");
pb.redirectErrorStream(true);
try {
Process proc = pb.start();
} catch (Exception e) {
e.printStackTrace();
}
... It appears to throw an error at Process proc = pb.start(), which is understandable, really.
Any answers would be greatly appreciated.
https://stackoverflow.com/a/17120829/524743
First element in array must be an executable. So you have to invoke cmd.exe in order to call you batch file.
ProcessBuilder builder = new ProcessBuilder(Arrays.asList(new String[] {"cmd.exe", "/C", "batchCommand"}));

Running simple CECopy in CMD using Java

I am trying to run a simple "cecopy" in java. I call "cmd.exe" and pass the command through. It creates the directories but doesnt carry out the copy.
Below is the command I am using, set as a string in java:
String cmd = "mkdir \"C:\\\\Dominos\\\\DATFiles\" >> log.txt\n"
+ "\n" +
"cecopy \"dev:\\Application\\\\MCL\\\\Projects\\\\Default\\\\aa.dat\" \"C:\\\\Dominos\\\\DATFiles\");
Below is how I am calling command prompt to execute the DOS statement:
Runtime rt = Runtime.getRuntime();
try {
Process p = rt.exec("cmd.exe /c" + cmd); // Call CMD
p.waitFor(); // Wait till CMD finishes
} catch (InterruptedException | IOException ex) {
Logger.getLogger(readData.class.getName()).log(Level.SEVERE, null, ex);
}
Any help?
Thanks in advance!
You can use process builder. It handles commands with arguments neatly.
ProcessBuilder processBuilder = new ProcessBuilder();
p.command("cmd_to_run", "args_if_any");
p.start();

Firing command using java runtime class on a windows machine

I am trying to fire the following command on a windows(that came as part of a product we have bought):
start /wait setup /z"/sfC:\temp\input_file.txt" /s /f2"C:\temp\newlogfile.log"
Now the sad part is that I am failing to run the command using a java program that I wrote. (I have to run it as a part of something else, hence the need of running it through java)
Here is my code:
String[] cmd = new String [6];
cmd[0] = "start";
cmd[1] = "/wait";
cmd[2] = "setup";
cmd[3] = "/z\"/sfC:\\temp\\input_file.txt\"";
cmd[4] = "/s";
cmd[5] = "/f2\"C:\\temp\\newlogfile.log\"";
try
{
Runtime.getRuntime().exec(cmd);
}
catch(IOException e)
{
e.printStackTrace();
}
Please tell me what I am doing wrong here.
This is the output I am getting:
java.io.IOException: CreateProcess: start /wait setup /z"/sfC:\temp\input_file.txt" /s /f2"C:\temp\newlogfile.log" error=2
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(ProcessImpl.java:108)
at java.lang.ProcessImpl.start(ProcessImpl.java:56)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:466)
at java.lang.Runtime.exec(Runtime.java:607)
at java.lang.Runtime.exec(Runtime.java:480)
at SilentAgent.fireCommand(SilentAgent.java:316)
at mainClass.main(mainClass.java:15)
Try with this:
String[] cmd = {
"cmd.exe",
"/c",
"start",
"/wait",
"setup",
"/z\"/sfC:\\temp\\input_file.txt\"",
"/s",
"/f2\"C:\\temp\\newlogfile.log\""
};
Runtime.getRuntime().exec(cmd);
Reason: start is an internal command available only from inside a cmd shell.
Do this way:-
Runtime.getRuntime().exec(new String[] {
"start ",
"/wait ",
"setup ",
"/z\"/sfC:/temp/input_file.txt\" ",
"/s ",
"/f2\"C:/temp/newlogfile.log\""});
Are you sure that you java program is located in the same directory of the 'start' program?
If not, pass the command string as a whole string
try {
String command = "start /wait setup /z\"/sfC:\\temp\\input_file.txt\" /s /f2\"C:\\temp\\newlogfile.log\"";
// The third parameter is the current working directory
Process p = runtime.exec(c, null, new File());
} catch (Exception e) {
e.printStackTrace();
}

Categories

Resources