Run batch with java return error - java

I need send parameter and execute batch file from java code. I used this method:
private void run(){
if (atmUsernameField.getText().length() > 0 &&
atmPasswordField.getText().length() > 0 &&
serverURLField.getText().length() > 0){
String atmUsername= atmUsernameField.getText();
String atmPassword = atmPasswordField.getText();
String url = serverURLField.getText();
String userHomePath = System.getProperty("user.home");
userHomePath = userHomePath + File.separator + "INFOKIOSK" + File.separator + "device_jar";
String fileName = userHomePath + File.separator + "restart.bat";
if (SystemUtils.IS_OS_WINDOWS_XP || SystemUtils.IS_OS_WINDOWS) {
try {
String processID = ManagementFactory.getRuntimeMXBean().getName();
int endIndex = processID.indexOf("#");
processID = processID.substring(0, endIndex);
new ProcessBuilder("cmd", "/c", "start " + fileName, processID, atmUsername, atmPassword, url).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
this is the restart.bat:
TASKKILL /F /PID %1 /T
cd /d %~dp0
java -jar device.jar --atm.autoload.page=%4 --atm.username=%2 --atm.password=%3 -debug
restart.bat need at first killed process where PID = processID
and go to folder where is located he
and running device.jar with parameters.
When I runnin this code on Windows 7 machine, code is worked. If running on Windows XP SP3 machine return error "Not Found C:\Documents ...."
I need running this code on Windows XP machine. where the error is, why the code does not work?

userHomePath contains spaces on winXP.
On Win7 it does not anymore.
Try to add quotes as shown below, it will work in either environment:
new ProcessBuilder("cmd", "/c", "start \"" + fileName + "\"", processID, atmUsername, atmPassword, url).start();
Maybe you'll need to add quotes in your .bat too
cd /d "%~dp0"

Related

How can I start a .jar in xterm with args?

if (args.length == 0&&runningFromIntelliJ()==false) {
String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
if (OS.indexOf("win") >= 0) {
String path = CODE.run.class.getProtectionDomain().getCodeSource().getLocation().getPath().substring(1);
String decodedPath = null;
try {
decodedPath = URLDecoder.decode(path, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
Runtime.getRuntime().exec("cmd"+" /c start java -jar \"" + decodedPath + "\" run");
} catch (IOException e) {
e.printStackTrace();
}
System.exit(0);
}
}
}
This Code is Starting a programm in cmd after i double clicked it. the problem is that it only works in windows And I want to run it on my raspberry pi. The problem now is that I habe no Idea how a can start a .jar with args in xterm.
runningFromIntelliJ() is just testing if I am running the programm in IntelliJ and skips that part if I do.
It seems like your app will do nothing once there's an argument passed to the jar.
if(args.length==0)
will be false hence the whole if. If you have other code to run with Arguments, try this:
java -jar yourJar.jar "arg 1" arg2#
Otherwise, review your code.
Here is one way to start a program with xterm.
xterm -hold -e '/bin/bash -c "ls -l"'
In this example, the program is simply the ls command, but it should be self-explanatory how to use it for java; just use the example found in another answer.
In your java code, what that looks like is:
Runtime.getRuntime().exec(String.format("xterm -hold -e '/bin/bash -c \"%s\"'", "java -jar '" + decodedPath + "' run"));
or without a shell:
Runtime.getRuntime().exec(String.format("xterm -hold -e 'java -jar \"%s\" run'", decodedPath));

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

backup mysql database java code

I tried to run the following code which is to create a backup of my database but it shows some run time errors.
But, I tried to run the System.out.println() output part, (which I've commented in the given code) in mysql shell and it worked.
It shows io file problem. Plz somebody help me.
package files;
public class tableBackup_1 {
public boolean tbBackup(String dbName,String dbUserName, String dbPassword, String path) {
String executeCmd = "mysqldump -u " + dbUserName + " -p" + dbPassword + " --add-drop-database -B " + dbName + " -r " + path;
Process runtimeProcess;
try
{
System.out.println(executeCmd);//this out put works in mysql shell
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0)
{
System.out.println("Backup created successfully");
return true;
}
else
{
System.out.println("Could not create the backup");
}
} catch (Exception ex)
{
ex.printStackTrace();
}
return false;
}
public static void main(String[] args){
tableBackup_1 bb = new tableBackup_1();
bb.tbBackup("test","harin","1234","C:/Users/Master/Downloads/123.sql");
}
}
mysqldump -u harin -p1234 --add-drop-database -B test -r C:/Users/Master/Downloads/123.sql
java.io.IOException: Cannot run program "mysqldump": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(ProcessBuilder.java:460)
at java.lang.Runtime.exec(Runtime.java:593)
at java.lang.Runtime.exec(Runtime.java:431)
at java.lang.Runtime.exec(Runtime.java:328)
at files.tableBackup_1.tbBackup(tableBackup_1.java:12)
at files.tableBackup_1.main(tableBackup_1.java:34)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(ProcessImpl.java:81)
at java.lang.ProcessImpl.start(ProcessImpl.java:30)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:453)
... 5 more
Please check whether your Global PATH environment variable has <Path to MySQL>\bin in it (Do a echo %PATH% and see). Effectively you should be able to type your System.out.println() content in a Plain DOS prompt and should be able to run it.
Even with that if it doesn't work try changing the code to execute like below
runtimeProcess = Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", executeCmd });
This should ideally fix the issue.
UPDATE:
If you don't have it in the PATH environment variable change the code to following
String executeCmd = "<Path to MySQL>/bin/mysqldump -u " + dbUserName + " -p" + dbPassword + " --add-drop-database -B " + dbName + " -r " + path;
runtimeProcess = Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", executeCmd });
i tried this one but it didn't work so i replaced it with
this runtimeProcess = Runtime.getRuntime().exec(executeCmd);
and it worked
I solved this problem by giving full path to mysqldump.exe
You can get SO environment variables by
Map<String, String> env = System.getenv();
final String LOCATION = env.get("MYSQLDUMP");
I setup the system variable like this :
Variable Name : MYSQLDUMP
Value : D:\xampp\mysql\bin\mysqldump.exe
Now just execute this code below,
String executeCmd = LOCATION+" -u " + DBUSER + " --add-drop-database -B " + DBNAME + " -r " + PATH + ""+FILENAME
Process runtimeProcess = = Runtime.getRuntime().exec(executeCmd);
Note : If you don't have configured password for mysql server just remove the -p PASSWORD attribute from the code. And don't forget to restart your computer after creating a new system variable.

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