Lets say, that i have launched simple Java application, that outputs some strings to standart console using following command:
Runtime.getRuntime().exec("Path:/to/app.exe");
What i need is to gather all data, that launched app throws to the console. Is it possible? Thanks.
Paul.
You can use ProcessBuilder and get its IutputStream. Here is simple example:
public static void main(String[] args) throws Exception {
String[] processArgs = new String[]{"ping","google.com"};
Process process = new ProcessBuilder(processArgs).start();
BufferedReader in = new BufferedReader(new InputStreamReader(
//I'am using Win7 with PL encoding in console -> "CP852"
process.getInputStream(), "CP852"));
String line;
while ((line = in.readLine()) != null)
System.out.println(line);
in.close();
System.out.println("process ended");
}
Related
I use this method call_shell() to connect Java and shell.
private static String call_shell(String command) throws IOException, InterruptedException{
Process proc = Runtime.getRuntime().exec(command);
if(proc.waitFor() != 0){
System.out.println("wrong in shell.");
}
String s = null;
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
while((s = br.readLine()) != null){
sb.append(s).append("\r\n");
}
br.close();
return sb.toString();
}
However, when I call this method using System.out.println(call_shell("/usr/local/bin/redis-server"));, it will get blocked on the console, because of redis-server will block the bash.
So I use System.out.println(call_shell("/usr/local/bin/redis-server &")); and want to run it background. However, it turns out an error which is
wrong in shell.
24759:C 21 Apr 16:45:47.718 # Fatal error, can't open config file '&'
How can I run it background?
I have a function in java which is being executet on my raspberry pi and should send a signal to toggle the targeted sockets state to on / off.
Thats my current function:
public static void rcswitch(int housecode,int unitcode, int onoff) throws InterruptedException, IOException {
String housestring = Integer.toString(housecode);
String unitstring = Integer.toString(unitcode);
String onoffstring = Integer.toString(onoff);
ProcessBuilder builder = new ProcessBuilder("/bin/bash", "-c", "sudo /home/pi/rcswitch-pi/send", housestring, unitstring, onoffstring);
Process proc = builder.start();
BufferedReader reader =
new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
}
However, it doesn't seem like the terminal is receiving the command as it does not output anything. It should show something like "command received" and execute it then. When I normally execute the /send command in the terminal it works just fine. In eclipse it just works fine and throws the expected error.
Thanks for your answers :)
It is most likely that an error has occured while executing the command. Keep in mind that Process#getInputStream() does not include standard error stream of the process. You should use Process#getErrorStream(). Something like:
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String line = null;
while((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
I am messing with Runtime.getRuntime(), but I don't think it really what I want.
I want something that has both user input, and output that goes to stdout. I would like a whole seperate program to get launched, basically.
Grae
Doing this:
Process process = Runtime.exec( "somecommand.exeorwhatever" );
Will run a completely separate process. Then you can use:
InputStream in = process.getInputStream();
InputStream err = process.getErrorStream();
OutputStream out= process.getOutputStream();
You can use Process created with ProcessBuilder.start() method and use its input and output streams.
Here is simple example:
public static void main(String[] args) throws Exception {
String[] processArgs = new String[]{"ping","google.com"};
Process process = new ProcessBuilder(processArgs).start();
BufferedReader in = new BufferedReader(new InputStreamReader(
//I'am using Win7 with PL encoding in console -> "CP852"
process.getInputStream(), "CP852"));
String line;
while ((line = in.readLine()) != null)
System.out.println(line);
in.close();
System.out.println("process ended");
}
I am trying to execute JAD decompiler on class file from code:
Process p = Runtime.getRuntime().exec("c:\\1\\jad.exe c:\\1\\EIn.class");
//All paths are correct, "c:\\1\\jad.exe c:\\1\\EIn.class" wotks when I run it in cmd
When I debug i don't get any errors, debugger moves to the next line...
if I put:
int res = p.waitFor();
It just hangs.
Update:
BufferedReader in = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String str = null;
while ((str = in.readLine()) != null) { //Stucks here
}
Is the jad decompiler waiting on input from you via stdin?
To see the errors that you are getting, consume the getOutputStream and getErrorStream to see what the decompiler is writing out.
You can use the ProcessBuilder class to make redirecting streams a little more pleasant.
public static void main(String[] args) throws Exception {
String[] cmd = { "c:\\1\\jad.exe", "-c:\\1\\EIn.class" };
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
}
This is a TRAP in Java ,please just have a look at this page,you will get more than you wanna!
In Java, I want to be able to execute a Windows command.
The command in question is netsh. This will enable me to set/reset my IP address.
Note that I do not want to execute a batch file.
Instead of using a batch file, I want to execute such commands directly. Is this possible?
Here is my implemented Solution for Future Reference:
public class JavaRunCommand {
private static final String CMD =
"netsh int ip set address name = \"Local Area Connection\" source = static addr = 192.168.222.3 mask = 255.255.255.0";
public static void main(String args[]) {
try {
// Run "netsh" Windows command
Process process = Runtime.getRuntime().exec(CMD);
// Get input streams
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
// Read command standard output
String s;
System.out.println("Standard output: ");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// Read command errors
System.out.println("Standard error: ");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
Runtime.getRuntime().exec("netsh");
See Runtime Javadoc.
EDIT: A later answer by leet suggests that this process is now deprecated. However, as per the comment by DJViking, this appears not to be the case: Java 8 documentation. The method is not deprecated.
Use 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.
}
You can run the command with Runtime.getRuntime().exec("<command>") (eg. Runtime.getRuntime().exec("tree")). But, this will only run executables found in path, not commands like echo, del, ... But only stuff like tree.com, netstat.com, ... To run regular commands, you will have to put cmd /c before the command (eg Runtime.getRuntime().exec("cmd /c echo echo"))
public static void main(String[] args) {
String command="netstat";
try {
Process process = Runtime.getRuntime().exec(command);
System.out.println("the output stream is "+process.getOutputStream());
BufferedReader reader=new BufferedReader( new InputStreamReader(process.getInputStream()));
String s;
while ((s = reader.readLine()) != null){
System.out.println("The inout stream is " + s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
This works.
Runtime#exec().