I try to launch a batch file from my Java application, but I only get an error window. It says:
"1" could not be found. Make sure that you used the right name and
repeat the process
(Free translation from german Windows 10). "1" is the number I try to give to the batch file.
I try to launch from a directory which contains spaces, e.g.: C:\user\my stuff\ etc.
Here is the specific code I am using:
String[] commands = {"cmd", "/c" , "start", batchfile.toString() , String.valueOf(ParameterNumber)};
Process p = Runtime.getRuntime().exec(commands);
batchfile is a valid path written like this: C:\Users\Admin\directory and stuff\
ParameterNumber is a valid int between 1 and 100.
The first parameter of start is an application title (run start /? to see the minihelp). You may use an empty string.
However in this case start isn't necessary, simply remove it from commands.
Related
I am trying to use ProcessBuilder in Java and I am not quite getting how to split up my arguments for it. For example, this command + arguments find . -name 'rc*'. Here below are few different argument splits and none of them are giving me the correct result. Any idea what I am doing wrong in the argument splitting?
//This is obvious error since I mixed arugments with the command
processBuilder.command("find . -name 'rc*'").directory(new File("/etc"))
//Gives me exit code 1 and no results
processBuilder.command("find", ". -name 'rc*'").directory(new File("/etc"))
//Gives me also exit code 1 and no results
processBuilder.command("find", ".", "-name", "'rc*'").directory(new File("/etc"))
//Gives me also exit code 1 and no results
processBuilder.command("find", ". -name", "'rc*'").directory(new File("/etc"))
//Gives me also exit code 1 and no results
processBuilder.command("find", ".", "-name 'rc*'").directory(new File("/etc"))
EDIT
When I tried to add .inheritIO(), and split all arguments, to this it worked partially that is I got printouts for files that have Permission denied.
processBuilder.command("find", ". -name 'rc*'").directory(new File("/etc")).inheritIO();
but as before it did not list my other "rc" files.
Listing all rc files in /etc directory:
//Here should be at least dozen files that print out when I use the command in terminal
Exit code: 1
find 'someFileName': Permission denied
find 'someFileName': Permission denied
find 'someFileName': Permission denied
My process and printout part
Process b;
b.processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(b.getInputStream()));
String line = "";
while((line = reader.readLine()) != null){
System.out.println(line);
}
SECOND EDIT
The thing is that if I change the ProcessBuilder command to a similar command (I guess) then it prints out the resulting files with no prob with the same code - i.e. I changed the command to ls -a like
processBuilder.command("ls","-a").directory(new File("/etc")).inheritIO();
//and then activate the process and print it just as before and all good ```
The launch is from Java so there is no need to escape the find parameter rc* with single quotes. A shell such as bash would expand rc* to actual files prefixed with "rc" in the current directory (and use wrong search value), but Java will not do that. Also every parameter must be in its own string:
processBuilder.command("find", ".", "-name", "rc*").directory(new File("/etc"));
or
processBuilder.command("find", "/etc", "-name", "rc*");
If find is reporting a lot of errors you may get problem that the process freezes because you don't read STDERR at same time as STDOUT. You can choose between running threads to consume streams, or redirecting STDERR->STDOUT, or send both or merged streams to a file with Process.redirectOutput(File) and Process.redirectError(File) before calling processBuilder.start(). Read this answer.
When I tried to run Ansible with Runtime.getRuntime().exec with Java
Here is what I did:
String[] cmd = {"ansible-playbook", "/path/to/playbook", "--extra-vars", "'{\"filePath\":\"/path/to/file\"}'"};
Process process = Runtime.getRuntime().exec(cmd, null);
I got error message like this:
FAILED! => {"failed": true, "msg": "'filePath' is undefined"}
However when I executed the same command with terminal:
ansible-playbook /path/to/playbook --extra-vars '{"filePath":"/path/to/file"}'
Everything was fine...
I think there must be some differences between the command I ran in terminal and Java, maybe apostrophe or quotation mark ?
I'm wondering is there any way to get the real executed command of Runtime.getRuntime().exec? Just like I can get command line history of some user by history...
You are adding additional quotes in your third parameter:
"'{\"filePath\":\"/path/to/file\"}'"
If you do this, you're not executing the same command in your shell as you have above. You're actually executing (in bash):
ansible-playbook /path/to/playbook --extra-vars ''\''{"filePath":"/path/to/file"}'\'''
You don't need the single quotes around the value here: because you're passing these values directly, you don't have to worry about the quoting that you'd have to do in a shell. You can simply use:
"{\"filePath\":\"/path/to/file\"}"
So I'm creating a Java program and I want to make it so that you can ask it to open a program.
But, here's the catch, I want the program it opens to be taken from the user input, right now I'm trying to change this
try{Process p = Runtime.getRuntime().exec("notepad.exe");}
catch(Exception e1){}
Into something that opens a program that you asked it to open.
Here's an example of what I want:
User: Can you open chrome?
Program: Of course, here you go!
chrome opens
Could anyone tell me how I would be able to do this?
You can do it in two ways:
1.By Using Runtime:
Runtime.getRuntime().exec(...)
So, for example, on Windows,
Runtime.getRuntime().exec("C:\application.exe -arg1 -arg2");
2.By Using ProcessBuilder:
ProcessBuilder b = new ProcessBuilder("C:\application.exe", "-arg1", "-arg2");
or alternatively
List<String> params = java.util.Arrays.asList("C:\application.exe", "-arg1", "-arg2");
ProcessBuilder b = new ProcessBuilder(params);
or
ProcessBuilder b = new ProcessBuilder("C:\application.exe -arg1 -arg2");
The difference between the two is :
Runtime.getRuntime().exec(...)
takes a single string and passes it directly to a shell or cmd.exe process. The ProcessBuilder constructors, on the other hand, take a varargs array of strings or a List of strings, where each string in the array or list is assumed to be an individual argument.
So,Runtime.getRuntime.exec() will pass the line C:\application.exe -arg1 -arg2 to cmd.exe, which runs a application.exe program with the two given arguments. However, ProcessBuilder method will fail, unless there happens to be a program whose name is application.exe -arg1 -arg2 in C:.
You can try it with like. Pass whole path of where you install chrome.
try{
Process p = Runtime.getRuntime().exec("C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe");
}
catch(Exception e1){
}
When using exec, it is essentially the same as if you were using the command line on windows. Open Command Prompt, type open, and see if it gives details as to how it opens files. If not, find the opener. Usually when dealing with command line operations, there are multiple parameters that are required for opening files/applications. An example of this would be for opening the "TextEdit.app" application on a mac.
Process p = Runtime.getRuntime().exec("open -a TextEdit.app");
Terminal(for mac) would open the app using the -a flag, meaning "application." You could open a file doing:
Process p = Runtime.getRuntime().exec("open filename.file_ext -a TextEdit.app");
The second one will tell the computer to find the application named <app_name>.app and open the file filename.file_ext
I know this is not going to work for a windows machine, but it's only to show how to use the command line operations for opening files and applications. It should be similar for windows though.
Hope this helps
I know that by using the command in the terminal
date --set="2011-12-07 01:20:15.962"
you would actually be able to change the System clock, so I tried it in Java and came up with the following statement
Process p = Runtime.getRuntime().exec("date --set=\"2011-12-07 01:20:15.962\"");
but it was not able to set the clock.
Do you have any idea guys how it may be able work?
Premise:
The machine is Slackware,
The privilege is root level
There are two problems with this line of code:
Process p = Runtime.getRuntime().exec("date --set=\"2011-12-07 01:20:15.962\"");
You did not wait for the process to complete (see also http://docs.oracle.com/javase/6/docs/api/java/lang/Process.html#waitFor())
Parameters should be separated from program name, try this:
"date", "-s", "2011-12-07 01:20:15.962"
Alternatively, invoke shell as the process, and pass in a line of code:
.exec("sh", "-c", "date --set=\"2011-12-07 01:20:15.962\"")
Process p=Runtime.getRuntime().exec(new String[]{"date","--set","2011-12-07 01:20:15.962"});
The above statement worked like magic. #Howard Gou was right with "Parameters should be separated from program name"
The parts of the command statement should be passed by using a String array.
I'm testing tidesdk.
I have a java program that reads from standard input.
I run the program through the console console
java -cp MyProgram.jar package.MyMainClass
And then execute commands and get results.
there any way to do with tidesdk?
Edit:
The problem was that calls the java program with a list of one element (which contained the command separated by spaces)
It solved with passing every word to a item of list (and removing the spaces).
Right now I have porblemas to write standard input. This is what I'm trying.
var input = Ti.Process.createPipe();
var process = Ti.Process.createProcess({
args:['java', '-cp', 'C:/.../MyProgram.jar', 'package.MyMainClass'],
stdin: input
});
//process.setOnReadLine(function(line) { alert(line) });
process.launch();
input.write("comand parameter1 parameter2\n"); //This line does not work
The java program starts. But never gets a command.
Checkout Documentation of Ti.Process.createProcess. That is exactly what you are looking for:
http://tidesdk.multipart.net/docs/user-dev/generated/#!/api/Ti.Process