I am trying to use the exec function. The path to the executable contains spaces and this is giving me grief
My code looks like this
Runtime.getRuntime().exec("\"C:\\Program Files (x86)\\ASL\\_ASL Software Suite_installation.exe\"", null, new File("\"C:\\Program Files (x86)\\ASL\\_ASL Software Suite_installation\""));
When this is executed I get an exception -
Cannot run program ""c:\Program"
I would be grateful if someone can give me some help in solving this
Thanks in advance
From Runtime.exec(String command, String[] envp, File dir):
Executes the specified string command in a separate process with the specified environment and working directory.
This is a convenience method. An invocation of the form exec(command, envp, dir) behaves in exactly the same way as the invocation exec(cmdarray, envp, dir), where cmdarray is an array of all the tokens in command.
More precisely, the command string is broken into tokens using a StringTokenizer created by the call new StringTokenizer(command) with no further modification of the character categories. The tokens produced by the tokenizer are then placed in the new string array cmdarray, in the same order.
This means the first string is broken into tokens, regardless of the outer quotes. Use the Runtime.exec(String[] cmdarray, String[] envp, File dir) version to avoid the tokenization of the executable path.
Or, use ProcessBuilder:
File d = new File("C:/Program Files (x86)/ASL/_ASL Software Suite_installation");
ProcessBuilder pb = new ProcessBuilder(d.getAbsolutePath() + "/main.exe");
Process p = pb.directory(d)
.start();
See:
Why should avoid using Runtime.exec() in java?
ProcessBuilder vs Runtime.exec()
You don't need to quote the filenames again. Java will take care of it for you just give the proper filename as a string like so
Runtime.getRuntime().exec(
"C:\\Program Files (x86)\\ASL\\_ASL Software Suite_installation.exe",
null,
new File("C:\\Program Files (x86)\\ASL\\_ASL Software Suite_installation"));
Related
I am using the below code to open the "sample.html' file.
String filename = "C:/sample.html";
String browser = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe";
Runtime rTime = Runtime.getRuntime();
Process pc = rTime.exec(browser + filename);
pc.waitFor();
However, I am getting the below error.
java.io.IOException: Cannot run program "C:/Program": CreateProcess error=2, The system cannot find the file specified
Could someone please help me figure this. Thanks in advance.
Runtime.exec(String) automatically splits the string at spaces, assuming the first token is the command name and the rest are command line parameters. Also you do not have a space between browser and file, although that is not the root cause of the problem.
It thinks you want to run "C:/Program" with two command line arguments:
"Files"
"(x86)/google/Chrome/Application/chrome.exeC:/sample.html"
Use Runtime.exec(String[]) instead, that way you have full control over what is what:
String[] command = new String[]{browser, filename};
Runtime.exec(command);
Try this.
String filename = "C:\\sample.html";
String browser = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe";
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec(new String[] {browser, filename});
} catch (IOException e) {
e.printStackTrace();
}
Stop using Runtime.exec(String) - the problem is in how it processes the single string input.
The error message indicates how/where it is failing: note that it stops after "C:/Program" (or, the first space). This indicates that exec parsed the string "incorrectly" and thus isn't even looking for the correct executable.
Cannot run program "C:/Program"
Instead, consider the use of ProcessBuilder. While the usage is still system-dependent, ProcessBuilder allows separation of the executable file-name (and need to deal with it specially) and the arguments and does it's darnedest to invoke the target correctly.
String filename = "C:\\sample.html";
String browser = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe";
ProcessBuilder pb = new ProcessBuilder(browser, filename);
// setup other options ..
// .. and run
Process p = pb.start();
p.waitFor();
From what I can tell, in Windows, ProcessBuilder will wraps the individual components in quotes; this can create a different problem when arguments contain quotes..
Parameters must be passed separately:
Process pc = rTime.exec(new String[]{browser, filename});
Using exec() is not like using the command line - you can not use spaces to delimit the command from its parameters. Your attempt would try to execute a command whose path was the concatenation of the exec and the filename as one giant string.
I am trying to expand a zip file using 7zip but I keep getting the 7zip Usage printout.
The zip exist in c:\temp
The same command succeed in batch window :
C:\TEMP>7z x "tryThis.zip"
I tried adding the workdir path to the file,And also without the working dir,
nothing help. - I can probably run this using CMD/c command but I prefer to keep the code clean
What am I doing wrong?
Thank you!
String pathTo7ZipExe = "c:\\program files\\7-zip\\7z.exe";
String fileName ="tryThis.zip";
String workingDir = "c:\\temp\\";
Process process = Runtime.getRuntime().exec(
new String[]{pathTo7ZipExe},
new String[]{" x \"" + fileName +"\""},
new File(workingDir));
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
// wait for zip to end.
int exitVal = process.waitFor();
Please have a look at the documention for Runtime.exec
What you were actually trying to do is calling 7-zip without arguments and providing the arguments as your environment. Environment is something like Windows PATH etc.
so you would probably want to do something like:
Runtime.getRuntime().exec(new String[]{pathToZipExe, "x", fileName}, null, new File(workingDir));
On the other hand I would strongly advise to have a look on ZipInputStream which is included in java - using that you can also unpack zip files.
Cheers
You're invoking the overload of exec which accepts envp array as the second argument. This envp array is not for arguments at all, so actually you don't pass any arguments: that's why you get the usage printout.
Quotes and spaces aren't themselves part of arguments: they are used for separation into argv (with minor reservations, it's also true for Windows: that's how CommandLineToArgW works, even though full original command line with quotes and spaces is always available).
So it should be something like this:
Runtime.getRuntime().exec(new String[]{pathTo7ZipExe, "x", fileName},
new String[]{}, new File(workingDir));
(too bad I don't know Java, so the code might be unidiomatic, but it should work).
I am writing a Java Swing application in Java that serves as a frontend for the ffmpeg command. It inputs the folder and the file name from the user and adds many more parameters that are constantly displayed in JTextField. User can edit the final command in the text field that it about to be called.
This works in both Windows and Linux:
Process ffmpeg = Runtime.getRuntime().exec(command, null, new File(current_working_folder));
command is a string. It is formatted depending from the OS, so that the path is always given in full (absolute path) and the slashes are appropriate for the given OS.
In Windows and Linux, it is possible to execute ffmpeg command by enclosing the folder and file names in "....". In Windows, this formatting ultimately works through Runtime.getRunTime.exec().
However, in Linux, this does not work through Runtime.getRunTime.exec(). The quotation marks are perhaps misunderstood "....".
Any advice on this?
Try passing your command as an array, rather than a string using this method: Runtime.exec(String[] cmdarray, String[] envp, File dir).
For example, instead of :
Runtime.getRuntime().exec("ffmpeg -i video_origine.avi video_finale.mpg", null, new File(current_working_folder));
use:
Runtime.getRuntime().exec(new String[]{"ffmpeg", "-i", "video_origine.avi", "video_finale.mpg"}, null, new File(current_working_folder));
Am trying to execute the a bat file with some arguments through a JAVA programmes . the arguments are file name with full path, And this path had some folder name with space, which are creating issue and giving me the following error
Error: 'D:\Documents' is not recognized as an internal or external
command
the code is as below
String command = "D:\Documents and Settings\ A.bat" + " " D:\Documents and Settings\B.xml
1. process = Runtime.getRuntime().exec(new String[] {"cmd.exe","/c",command});
2. process.waitFor();
3. exitValue = process.exitValue();
You need to escape the \ in your string (i.e. doubling them: D:\\Documents), but that is not the problem. You can try to escape the spaces Documents\\ and\\ Settings or you use the exec method that does this for you. Just dont build the command line by yourself. Better use ProcessBuilder for starting processes.
String command = "\"D:\Documents and Settings\\" A.bat" + " \"D:\Documents and Settings\B.xml\""
Escape double quotes, so you can include double quotes in the literal, to give:
cmd.exe /x "D:\Documents and Settings\" A.bat "D:\Documents and Settings\B.xml"
I was trying to do the same thing. I googled whole day but didn't make it work. At Last I handled it in this way, I am sharing it if it comes to any use of anybody :
String command = "A.bat D:\\Documents and Settings\\B.xml";
File commandDir = new File ( "D:\\Documents and Settings ");
String[] cmdArray = { "cmd.exe", "/c", command };
1. Process process = Runtime.getRuntime().exec( cmdArray, null, cmdArray );
2. process.waitFor();
3. exitValue = process.exitValue();
I've spent a while searching on SO and the wider Internet and was about to post this as a new question when I came across this, which does seem identical to my issue...
I am trying to call a Windows batch file from Java. The batch file takes several arguments but just the first, which is a path to a data file, is of relevance to this problem. The cut-down command line that I have been experimenting with is essentially:
cmd /c c:\path\to\my\batchfile.bat c:\path\to\my\datafile.mdl
I'm using Apache Commons Exec which ultimately delegates to Runtime.getRuntime().exec(String[] cmdarray, String[] envp, File dir), the 'correct' version as opposed to the overloaded versions taking a single String command. Quoting of the arguments when they contain spaces is therefore taken care of.
Now, both the path to the batch file and/or the path to the data file can have spaces in them. If either the path to the batch file or the path to the data file have spaces in, then the batch file is executed. But if both have spaces in them then the path to the batch file is truncated at the first space.
This has to be a (Java or Windows?) bug, right? I've debugged right down to the native call to create() in java.lang.ProcessImpl and all seems ok. I'm on JDK1.6.
I have an exe file which takes a file name as input.
When I execute it as a command like:
xyz.exe c:\input.txt c:\ouput.txt
It all works as expected.
But how to execute this is java?
This is the one i used and am not getting the ouput in the files:
String[] str = {"c:/input.txt","c:/output.txt"};
Process p = rt.exec("c:/xyz.exe",str);
You're using the method:
public Process exec(String command,
String[] envp)
where envp is a (quote) "array of strings, each element of which has environment variable settings in the format name=value, or null if the subprocess should inherit the environment of the current process."
Try this instead:
String[] command = {"c:/xyz.exe", "c:/input.txt", "c:/output.txt"};
Process p = Runtime.getRuntime().exec(command);
// ...
Also read this article that explains the pitfalls of Runtime.exec(...): http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
Use Runtime.exec or Processbuilder API
I believe this should answer your question http://www.daniweb.com/software-development/java/threads/133710