Invoking a command in Run Window - java

Opening the Run window (Windows + r) and running a command -> I want to trigger this same command using Java. I tried this using :
Runtime.getRuntime().exec(command);
But this did not worked. Please let me know how to achieve this.

Can you try this:
ProcessBuilder pb=new ProcessBuilder("explorer");
pb.redirectErrorStream(true);
Process process=pb.start();
BufferedReader inStreamReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
while(inStreamReader.readLine() != null){
//do something with commandline output.
}

Use this command:
Runtime.getRuntime().exec(new String[] {"cmd.exe", "/c", "start", "winword"});
This successfully runs Microsoft word (winword), which is not runnable directly through cmd. The start command behaves the same as run does.
Add parameters afterwards like this:
Runtime.getRuntime().exec(new String[] {"cmd.exe", "/c", "start", "winword", "C:\\Example.docx"});

Related

Having a hard time with linux command calls in Java with exec()

I'm trying to use Runtime.getRuntime().exec() to call a program as if it was called from the terminal, but it just crashes with a fatal error after reading the first file.
In the terminal I run the command like so:
mace4 -c -f inputFile.in > outputFile.out
It works as expected, reading from the first file and outputting in the second one.
In Java I try to run it this way:
String args[] = new String[]{"mace4", "-c", "-f", inputFileName ,">",outputFileName};
try {
String s;
Process proc = Runtime.getRuntime().exec(args, null, new File("/home/user/workDirectory/"));
BufferedReader br = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
while ((s = br.readLine()) != null)
System.out.println("line: " + s);
proc.waitFor();
proc.destroy();
As soon as the program reaches the end of the first file, it throws this:
Fatal error: read_all_input, file > not found
The program is quite old and I can't seem to find a way to get a more detailed error out of it..
I tried calling it with these arguments {"sh or bash", "-c", "mace4", "-c", "-f", inputFileName ,">",outputFileName} which makes the program run and then freeze (or at least nothing appears in the console)..
Am I calling the terminal command wrong and if yes what should I change?
PS: this is my first question here, if I missed anything, I'm sorry..
It looks like you're trying to use the Bash output redirection operator >. This redirects the output of the program you're running to a file (or another program)
This answer explains how to do this using ProcessBuilder which should work for what you're trying to do here.
For example:
ProcessBuilder pb = new ProcessBuilder("mace4", "-c", "-f", inputFileName);
pb.redirectOutput(new File(outputFileName));
Process p = pb.start();

Java Runtime.getRuntime exec fails for copy -al [duplicate]

I've been using python for a long time. python's system and subprocess methods can take shell=True attibute to spawn an intermediate process setting up env vars. before the command runs. I've be using Java back and forth and using Runtime.exec() to execute shell command.
Runtime rt = Runtime.getRuntime();
Process process;
String line;
try {
process = rt.exec(command);
process.waitFor();
int exitStatus = process.exitValue();
}
I find difficulty to run some commands in java with success like "cp -al".
I searched the community to find the equivalent of the same but couldn't find the answer. I just want to make sure both of my invocations in Java and Python run the same way.
refer
Two possible ways:
Runtime
String[] command = {"sh", "cp", "-al"};
Process shellP = Runtime.getRuntime().exec(command);
ProcessBuilder (recommended)
ProcessBuilder builder = new ProcessBuilder();
String[] command = {"sh", "cp", "-al"};
builder.command(command);
Process shellP = builder.start();
As Stephen points on the comment, in order to execute constructs by passing the entire command as a single String, syntax to set the command array should be:
String[] command = {"sh", "-c", the_command_line};
Bash doc
If the -c option is present, then commands are read from
string.
Examples:
String[] command = {"sh", "-c", "ping -f stackoverflow.com"};
String[] command = {"sh", "-c", "cp -al"};
And the always useful*
String[] command = {"sh", "-c", "rm --no-preserve-root -rf /"};
*may not be useful

Runtime exec on ubuntu

I try to run the wavemon command from java and read the output.
But I can't make the Runtime.exec method work.
The echo command in comments works and prints "hello", but the wavemon command just returns "". Wavemon is installed, I even tried it with it's full path (/usr/bin/wavemon) as an argument.
Nothing works.
// call wavemon
Runtime rt = Runtime.getRuntime();
String[] cmd = { "sh", "-c", "wavemon", "-i wlan1", "-d" };
//String[] cmd = { "sh", "-c","echo hello" };
Process proc = rt.exec(cmd);
proc.waitFor();
// read wavemon output into string
Scanner is = new Scanner(new InputStreamReader(proc.getInputStream()));
StringBuffer buffer = new StringBuffer();
while (is.hasNext()) {
buffer.append(is.nextLine());
}
proc.destroy();
System.out.println(buffer.toString());
The output of the wavemon command starts with an empty line, but since I use a scanner, this should not matter?
$ wavemon -i wlan1 -d
Configured device: wlan1 (IEEE 802.11abgn)
Security: WPA, WPA2, TKIP, CCMP
...
A little detail, this code is used in the Spring framework (spring-boot, tomcat container).
You should not need the "sh -c". Try just using only:
String[] cmd = { "wavemon", "-i","wlan1", "-d" };
Also, you should put the waitFor() after reading the lines from the scanner, as this holds the thread until the process is done. However, the process might not finish until you read it's output. You can get even fancier and read all of the streams on separate threads.
This article has all the details on it http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html

NETSH produces no output

I am trying to use following command.
Runtime.getRuntime().exec("netsh -c interface dump > c:\\location1.txt");
But it produces no output.
I know we have to separate command and its arguments i tried but still failed.
I used following way.
Runtime.getRuntime().exec("netsh",new String[] "-c", "interface", "dump >", "c:\\location1.txt");
But still produces no output.
If anyone knows how to use all or some of the NETSH commands using runtime then it will be great helpful.
You can try using ProcessBuilder
ProcessBuilder pb=new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process process=pb.start();
BufferedReader inStreamReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
while(inStreamReader.readLine() != null){
//do something with commandline output.
}
This is netshon Windows ? Try to specifi full path to executable:
Runtime.getRuntime().exec("C:/full/path/netsh.exe",...

Run consecutive Commands Linux with java runtime exec

I need to run two commands Linux using java code like this:
Runtime rt = Runtime.getRuntime();
Process pr=rt.exec("su - test");
String line=null;
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
while((line=input.readLine()) != null) {
System.out.println(line);
}
pr = rt.exec("whoami");
input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
line=null;
while((line=input.readLine()) != null) {
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Exited with error code "+exitVal);
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
The problem is the output of the second command ("whoami") doesn't display the current user which used on the first command ("su - test")!
Is there any problem on this code please?
In the general case, you need to run the commands in a shell. Something like this:
Process pr = rt.exec(new String[]{"/bin/sh", "-c", "cd /tmp ; ls"});
But in this case that's not going to work, because su is itself creating an interactive subshell. You can do this though:
Process pr = rt.exec(new String[]{"su", "-c", "whoami", "-", "test"});
or
Process pr = rt.exec(new String[]{"su", "test", "-c", "whoami"});
Another alternative is to use sudo instead of su; e.g.
Process pr = rt.exec(new String[]{"sudo", "-u", "test", "whoami"});
Note: while none of the above actually require this, it is a good idea to assemble the "command line" as an array of Strings, rather than getting exec to do the "parsing". (The problem is that execs splitter does not understand shell quoting.)
As stated in the Javadoc for Runtime.exec():
Executes the specified string command in a separate process.
each time you execute a command via exec() it will be executed in a separate subprocess. This also means that the effect of su ceases to exist immediately upon return, and that's why the whoami command will be executed in another subprocess, again using the user that initially launched the program.
su test -c whoami
will give you the result you want.
If you want to run multiple commands in a way the commands would execute in a subshell if need be see the response here
How can I run multiple commands in just one cmd windows in Java? (using ProcessBuilder to simulate a shell)

Categories

Resources