I want to run a batch file using a java program, when I double click the .bat file it asks me to enter 'D' and after that it creates some folders in C drive, below is the contents of the .bat file:
xcopy "data" "C:\data" /S
xcopy "rapid" "C:\rapid" /S
subst x: /D
subst x: C:\
My Java code is as below:
try {
//C:\Desktop\Speed\view_R36_WD_Release\RAPID\switchToLive.Bat
String cmds[] = {"C:\\Users\\608521747\\Desktop\\Speed\\view_R36_WD_Release\\RAPID\\switchToDev.bat"};
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(cmds);
process.getOutputStream().close();
InputStream inputStream = process.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputStream);
BufferedReader bufferedrReader = new BufferedReader(inputstreamreader);
String strLine = "";
while ((strLine = bufferedrReader.readLine()) != null) {
System.out.println(strLine);
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
its not giving me any errors but it neither ask me to enter any value nor it creates any folder.
I want to know what do I need to do in java code so that it will ask me to enter the 'D' and then the .bat file should continue in a normal flow.
Any help is appreciated.
Your code needs to specify which program to execute your .bat file with.
Start narrowing down with the following fix.
p = run.exec("cmd.exe /c " + cmds);
Also try this link for similar code for similar question previously answered here.
Batch files are not executable files. So you will need to run cmd.exe and pass the batch file as parameter.
Please refer to this post - it addresses the same issue and provides a good solution - How do I run a batch file from my Java Application?.
Related
I want to run a .exe file from my java code,along with passing few arguments/options to the .exe file.
So basically, I did following:
BufferedReader br = null;
OutputResult out = new OutputResult();
String commandStr= "cmd.exe /C A-B/xyz.exe health -U admin -P admin";
Process p = Runtime.getRuntime().exec(commandStr);
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
out.add(line.trim());
}
NOTE: Here A-B is name of the directory in which xyz.exe is located.
But when the variable out is printed, it actually shows that it has nothing.
So instead of above code I modified it to the following:
BufferedReader bre = null;
OutputResult oute = new OutputResult();
String commandStr= "cmd.exe /C A-B/xyz.exe health -U admin -P admin";
Process p = Runtime.getRuntime().exec(commandStr);
bre = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line;
while ((line = bre.readLine()) != null) {
oute.add(line.trim());
}
Now here when the variable oute is printed, it shows the message,
'A-B' is not recognized as an internal or external command, operable program or batch file.
So my question is that why A-B is not being treated as a directory inside which the actual .exe file resides.
Please resolve the error if any one knows about this problem.
You should use a full path to your target xyz.exe - when you execute cmd.exe like that, it's not relative to the folder of your Java program, it's relative to C:\Windows\System32 therefore it can't see your A-B folder.
So, for example:
cmd.exe /C C:/A-B/xyz.exe health -U admin -P admin
And as #CSK correctly noticed, you can execute your .exe directly, without cmd.exe. For examle:
Process process = new ProcessBuilder("C:/A-B/xyz.exe", "health", "-U", "admin", "-P", "-admin").start();
I know that, for example, Java on Raspbian can't access directories with a space (for example /New Folder). I guess its some problem about how Raspbian considers the ' ' char when creating directory. Possibly, Windows might have the same problem with the '-' char. Can you rename the directory without any such chars and try again?
(I use a Mac so I'm unable to recreate the problem. Another option can be, if this is in fact not a problem to do with chars, to create a shell script from which the exe is executed and instead run this script via Java. I am only advising this because I used this method before without any problems.)
I have written some code for executing .bat file. which contains some
commands like setting java classpath,etc..And finally there is one command
which runs a Java class file.The HelloWorld class converts some xml file and generating a new xml file in some folder. When I double click .bat file, it executes fine,
but when I try to run I am not getting any output as I was getting through
double click the .bat file. How to make a batch execute and probably it would be nice
if I could see the results through Java console.
Following is MyJava code to execute the .bat file
public void run2() {
try {
String []commands = {"cmd.exe","/C","C:/MyWork/Java/classes/run.bat"} ;
Process p = Runtime.getRuntime().exec(commands);
BufferedReader in = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
And below the some commands which has been set to .bat file
set CLASSPATH=%CLASSPATH%;C:/MyWork/Java
set CLASSPATH=%CLASSPATH%;C:/MyWork/Java/classes
java -cp test.jar;test2.jar test.HelloWorld
Tried with "/C" commad as well. It does not execute. Actually it does not give effect of double click the .bat file. Is there any other way that I can try with?
I can see the contents inside the .bat file through Eclipse console. But it does not give the desired output. Desired output means when I double click .bat file, it executes well. But through java call, I can see the contents only .
When using cmd.exe use /C-Parameter to pass command:
String []commands = {"cmd.exe","/C","C:/MyWork/Java/classes/run.bat"} ;
according to this, the Windows CMD needs the /c argument, to execute commands like this. try this:
String []commands = {"cmd.exe","/c","C:/MyWork/Java/classes/run.bat"} ;
Windows uses \ backslash for Windows and MS-DOS path delimiter. Forward slash / is accepted by Java in the java.io package and translated to be a path delimiter, but will not be directly acceptable to Windows or accepted by the cmd.exe shell.
You may also need to specify either the working directory for the batch file to be executed in, or possibly a full path to the cmd.exe command interpreter.
See: Runtime.exec (String[] cmdarray, String[] envp, File dir)
String[] commands = {"C:\\Windows\\System32\\cmd.exe", "/c",
"C:\\MyWork\\Java\\classes\\run.bat"};
File workDir = new File( "C:/MyWork");
Process process = Runtime.getRuntime().exec( commands, null, workDir);
To verify if the batch file is run at all, add a pause command to the batch file. That will keep the window open so you can verify if the batch file is launched at all, and debug this stage-by-stage.
You do not read the error output of your batch file, therefore, you'll never see any error messages printed from there or from CMD.EXE itself. In addition, the sub-program may stall and just wait for you to read the error stream.
Please see related discussions here: How to make a java program to print both out.println() and err.println() statements?
I'm trying to convert files from png's to pdf using imagemagick and Java. I've got everything working to a place when I'm executing imagemagick command to actually merge multiple png's into one pdf. The command itself looks properly, and it works fine when executed in the terminal but my application gives me error showing that imgck can't open the file (even though it exists and I've set permissions to the folder to 777 :
line: convert: unable to open image `"/Users/mk/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/sch-java/print-1357784001005.png"': No such file or directory # error/blob.c/OpenBlob/2642.
This is my command :
/opt/local/bin/convert "/Users/mk/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/sch-java/print-1357784001005.png" "/Users/mk/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/sch-java/print-1357784001219.png" "/Users/mk/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/sch-java/complete-exportedPanel2013-01-1003:13:17.212.pdf"
And my Java code :
String filesString = "";
for (String s : pdfs){
filesString += "\""+ s + "\" ";
}
Process imgkProcess = null;
BufferedReader br = null;
File f1 = new File(pdfs[0]);
//returns true
System.out.println("OE: "+f1.exists());
String cmd = imgkPath+"convert "+ filesString+ " \""+outputPath+outName+"\"";
try {
imgkProcess = Runtime.getRuntime().exec(cmd);
InputStream stderr = imgkProcess.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
br = new BufferedReader(isr);
} catch (IOException e1) {
msg = e1.getMessage();
}
imgkProcess.waitFor();
while( (line=br.readLine() ) != null){
System.out.println("line: "+line);
}
The whole code is executed from a java servlet controller after getting request from a form. Any ideas what can cause this ? I'm using latest imgck, jdk, and osx 10.7 .
A few things:
When spawning anything but really trivial processes, it's usually better to use ProcessBuilder than Runtime.exec() - it gives you much better control
Even with ProcessBuilder, it often works better to write a shell script that does what you need. Then spawn a process to run the script. You get a lot more control in shell script than you do in ProcessBuilder
Remember that a spawned process is not a shell. It can't, for instance, evaluate expressions, or expand shell variables. If you need that, then you must execute a shell (like sh or bash). Better yet, write a shell script as described above
If all you need to do is to execute some ImageMagick commands, it would probably be easier to jmagick, a Java interface to ImageMagick - see http://www.jmagick.org/
Actually, since the you're assembling images into a PDF, the iText library - http://itextpdf.com is probably the best tool for the job, as it is native Java code, does not require spawning a native process, and will therefore be much more portable.
Solved it by adding all arguments to an arrayList and then casting it to String array.
ArrayList<String> cmd = new ArrayList<String>();
cmd.add(imgkPath+"convert");
for (int i=0, l=pdfs.length; i<l; i++){
cmd.add(pdfs[i]);
}
cmd.add(outputPath+outName);
imgkProcess = Runtime.getRuntime().exec(cmd.toArray(new String[cmd.size()]));
I need to execute a command line program with 2 arguments. However, it must execute in the working directory. i.e. "command arg1 arg2", not "c:\folder\subfolder\command arg1 arg2"
From other questions here, I've gotten up to using Runtime.exec(cmdArray, null, workingDirectory); but I keep getting "CreateProcess error=2, The system cannot find the file specified". I've checked, and both the path and file exist, so I don't know what is going wrong. Here is the code I'm using.
String [] fileName = {"mp3wrap.exe", "Clear_10", "*.mp3"};
String dirName = "E:\\Music\\New Folder\\zz Concatinate\\Clear_10";
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(fileName, null, new File(dirName));
BufferedReader input = new BufferedReader(new InputStreamReader
(pr.getInputStream()));
String line = null;
while ((line = input.readLine()) != null) {
System.out.println(line);
}//end while
int exitVal = pr.waitFor();
System.out.println("Exited with error code " + exitVal);
}//end try
catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}//end catch`
I'm getting this error:
java.io.IOException: Cannot run program "mp3wrap.exe" (in directory "E:\Music\New Folder\zz Concatinate\Clear_10"): CreateProcess error=2, The system cannot find the file specified
Give the whole path to mp3wrap.exe.
Java doesn't use the PATH to find mp3wrap.
--
Update after comment:
Okay - rereading the question, he asks how to start the program from inside the directory. If the program needs it, you have to start the Java program while being in this directory.
You might still have to give the whole path to the program, or start it with an indication to search for it in the current dir. I remember, that in Windows, the current dir is always searched. Other system differ here, so you would indicate the current dir with a dot, which works on Windows too: "./mp3wrap".
Alternatively you might want to try using ProcessBulder.start(). You can set env variables, the working directory and any args you want to pass to the Process that is spawned by the start() method. Look at the Java docs for a sample invocation.
I am developing a Linux-only Java application, and I need to execute a shell script in it. According to what I have read, the only way to execute that shell script is by extracting it from the jar file and executing it. The question is? How can I extract that shell script at runtime?
Thank you in advance
Unix does not know how to run scripts inside jar files. You must create a file (there are routines to create temporary files in the runtime) with the given content and then run that file - see How to run Unix shell script from Java code? for instructions. When done, delete it from the filesystem.
I found this question today ... i think there is a better answer:
unzip -p JARFILE SCRIPTFILE | bash
should do it.
where JARFILE is the path to the jar file
and SCRIPTFILE is the path WITHIN the jar of the script file to execute.
this will extract the file to stdout which is then piped to the shell (bash)
As someone has mentioned before, you can copy the content in the bundle resource to a temp location, execute the script, and remove the script in the temp location.
Here is the code to do that. Note that I am using Google Guava library.
// Read the bundled script as string
String bundledScript = CharStreams.toString(
new InputStreamReader(getClass().getResourceAsStream("/bundled_script_path.sh"), Charsets.UTF_8));
// Create a temp file with uuid appended to the name just to be safe
File tempFile = File.createTempFile("script_" + UUID.randomUUID().toString(), ".sh");
// Write the string to temp file
Files.write(bundledScript, tempFile, Charsets.UTF_8);
String execScript = "/bin/sh " + tempFile.getAbsolutePath();
// Execute the script
Process p = Runtime.getRuntime().exec(execScript);
// Output stream is the input to the subprocess
OutputStream outputStream = p.getOutputStream();
if (outputStream != null) {
outputStream.close();
}
// Input stream is the normal output of the subprocess
InputStream inputStream = p.getInputStream();
if (inputStream != null) {
// You can use the input stream to log your output here.
inputStream.close();
}
// Error stream is the error output of the subprocess
InputStream errorStream = p.getErrorStream();
if (errorStream != null) {
// You can use the input stream to log your error output here.
errorStream.close();
}
// Remove the temp file from disk
tempFile.delete();
Do not bundle the script in your jar in the first place. Deploy the scripts as independent files.