Run windows command from eclipse - java

I need to run the following command from eclipse..and print that result on eclipse console(Im comparing 2 files)
"fc /c/1 /n file1path file2path".
Here is my code
final Process p = Runtime.getRuntime().exec("cmd /c fc /c/1 /n file1path file2path");
new Thread(new Runnable() {
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line =new String();
try {
line = input.readLine();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
while (line != null) {
System.out.println(line);
line = input.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
p.waitFor();
But its not printing anything..What is wrong with the code??

The program is fine and works for me. The problem is in your command. Change your command and remove the cmd and extra /c flag. Also remove the invalid flag /c/1. Your final command should look like :-
final Process p = Runtime.getRuntime().exec("fc /c /n file1path file2path");

Related

Problem sshpass using Runtime.getRuntime().exec on java, but on cmd tunning fine

can someone solve this problem? I using sshpass for transfer file on java. Execute this command
Process proc = Runtime.getRuntime().exec(new String[] {"sshpass","-p", "password","scp","-r",getContext().getServletContext().getRealPath("/WEB-INF/file/"+today)+"/ Name#myip:/cygdrive/d/file"});
and the error doesn't show on java using runtime.exec but on the command line running well.
my code
try {
Process proc = Runtime.getRuntime().exec(new String[] {"sshpass","-p", "password","scp","-r",getContext().getServletContext().getRealPath("/WEB-INF/file/"+today)+"/ Name#myip:/cygdrive/d/file"});
// System.out.println(sshStr);
BufferedReader read = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
//--------------------check---------------------
printStream(proc.getInputStream(), "OUTPUT");
printStream(proc.getErrorStream(), "ERROR");
//--------------------check---------------------
try {
proc.waitFor();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
while (read.ready()) {
System.out.println(read.readLine());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
Using Runtime.exec(String), the string argument is split on whitespace, regardless of which quotes you've added. You have to use Runtime.exec(String[]) instead. This leads to:
Process proc = Runtime.getRuntime().exec(new String[] {
"sshpass",
"-p", "password",
"scp",
"-r", getContext().getServletContext().getRealPath("/WEB-INF/file/" + today) + "/ Name#myip:/cygdrive/d/file"
});

How to call a python program in java using Runtime

I want to call a python program with arguments from java. But my output is a blank. The code is here.
Python code is here:
import sys
print(sys.argv[1])
And the java code is here:
public class PrintNumber{
public static void main(String[] args){
Process proc;
try {
proc = Runtime.getRuntime().exec("python ../pythonProgram/pythonProgram/PrintN.py 30");
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
proc.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
I want to output 30, could somebody tell me where is the mistake?
You can try it out:
String command = "python /c start python ../pythonProgram/pythonProgram/PrintN.py";
int param = 30;
proc = Runtime.getRuntime().exec(command + param);
Reference: Run Python script by Java

java: parse output of execute command

i am running jdk on windows 7. I try to run a external software (pocketsphinx_continous.exe) within my java application. The software runs permanently (pocketsphinx_continous.exe) and prints some output to the console which i like to read by my java application.
if i run "pocketsphinx_continous.exe" with some params from the commandline all works well and i see the output from the software. After killing the process, i try to run it within my java application. But java print no output to the console.
This is my code:
public void start(){
try {
Runtime rt = Runtime.getRuntime();
String[] commands = {"D:/cmusphinx/pocketsphinx/bin/Release/x64/pocketsphinx_continuous.exe", "-hmm", "d:/cmusphinx/pocketsphinx/model/en-us/en-us", "-lm", "d:/cmusphinx/pocketsphinx/model/en-us/en-us.lm.bin", "-dict", "d:/cmusphinx/pocketsphinx/model/en-us/cmudict-en-us.dict", "-samprate", "16000/8000/48000", "-inmic", "yes"};
Process proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Java will only print "Here is the standard output of the command:" and nothing more. But it wont crash, its still running without any errors. It seems to me java will wait until the executed command is finished until it prints anything. But the software will run permanently and print some times new results ...
Any ideas?
Best regards
Mike
I suggest you do the following:
Process p = null;
ProcessBuilder b = new ProcessBuilder("D:/cmusphinx/pocketsphinx/bin/Release/x64/pocketsphinx_continuous.exe -hmm d:/cmusphinx/pocketsphinx/model/en-us/en-us -lm d:/cmusphinx/pocketsphinx/model/en-us/en-us.lm.bin -dict d:/cmusphinx/pocketsphinx/model/en-us/cmudict-en-us.dict -samprate 16000/8000/48000 -inmic yes");
try {
p = b.start();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader output = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
try {
while ( (line = output.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
Using ProcessBuilder you don't have to separate parameters. Just copy the whole command in a String.

Linux command "write all used jars by JVM to file" within Java

I want to know which jars are loaded by all the different running JVM's.
If I type
"lsof -p $PID | grep jar >> /somefile"
from the bash/command, it works beautifully! (replacing $PID with an actual process id). However, I would like to be able to do this from within a Java program. I would expect the following code to work but no file gets written:
public static void printCustomCommand(){
String[] pids = {"pidof java"};
String s;
try {
Process pidProcess = Runtime.getRuntime().exec("pidof java");
BufferedReader br = new BufferedReader(new InputStreamReader(pidProcess.getInputStream()));
pids = br.readLine().split(" ");
for (String pid : pids){
String cmd = "lsof -p " + pid + " | grep jar >> /somepath/mydumpfile";
Process p;
p = Runtime.getRuntime().exec(cmd);
System.out.println(p.waitFor());
}
//pids = new String(bo).split(" ");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
When I print the p.waitFor() command, it returns a 1 always, meaning according to the API documentation "something is incorrect".
http://docs.oracle.com/javase/6/docs/api/java/lang/Process.html#waitFor%28%29
The issue is that Runtime.exec() does not understand shell concepts such as "|".
Try this:
public static void printCustomCommand(){
String[] pids = {"pidof java"};
String s;
try {
Process pidProcess = Runtime.getRuntime().exec("/bin/bash -c pidof java");
BufferedReader br = new BufferedReader(new InputStreamReader(pidProcess.getInputStream()));
pids = br.readLine().split(" ");
for (String pid : pids){
String cmd = "/bin/bash -c lsof -p " + pid + " | grep jar >> /somepath/mydumpfile";
Process p;
p = Runtime.getRuntime().exec(cmd);
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
p.waitFor();
}
//pids = new String(bo).split(" ");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The problem is that exec runs a binary directly without invoking the shell. The "|" character is only recognized by the shell. The "-c" tells the shell to run a single command, and passes the entire command as the single argument.
Isn't that
Process pidProcess = Runtime.getRuntime().exec(new String[]{"pidof","java"});
?
And you cannot use pipes (|) in the exec method. The exec executes commands (executables) but pipes is part of the/a shell.

how to get error message when excuting java command?

I call a class which is located somewhere in a jar file (using java -classpath path/file.jar classname) within my java code.
This work well but only if the command is well formed. If I make a mistake the getRuntime().exect(command) just doesn't say anything. Bellow I have the working command invocation. I would like to get the error message when the command doesn't work. If I make a mistake in a cmd (windows) I get a proper error and I can fix it. But not within my java application.
I left a 'if(input.ready())' since if I don't the program freezes when the command line is incorrect. This happens when executing 'input.readLine()'.
// Execute a command with an argument that contains a space
String[] genKOSCommand = new String[] {
"java",
"-classpath",
Config.XDSI_TEST_KIT_HOME + "/xdsitest/lib/xdsitest.jar;"
+ Config.XDSI_TEST_KIT_HOME + "/xdsitest/classes",
"ca.etsmtl.ihe.xdsitest.docsource.SimplePublisher", "-k",
"C:/Softmedical/Viewer_Test/xdsi-testkit-2.0.4/xdsihome/usr/data/image14.dcm" };
Process child = Runtime.getRuntime().exec(genKOSCommand);
BufferedReader input = new BufferedReader(new InputStreamReader(
child.getInputStream()), 13107200);
String line = null;
if (input.ready()) {
while ((line = input.readLine()) != null) {
System.out.println(line);
}
try {
child.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Have any advice on how to get an error from the executed command?
Thank you
By using getErrorStream:
BufferedReader errinput = new BufferedReader(new InputStreamReader(
child.getErrorStream()));
When processing the input from the different streams, it is better to do it in a different thread (since those calls (readLine etc.) are blocking calls.
Here's a bit more complete piece of code to print out errors received upon running some command via Process/Runtime:
final String command = "/bin/bash -c cat foo.txt | some.app";
Process p;
try {
p = Runtime.getRuntime().exec(command);
} catch (final IOException e) {
e.printStackTrace();
}
//Wait to get exit value
try {
p.waitFor();
final int exitValue = p.waitFor();
if (exitValue == 0)
System.out.println("Successfully executed the command: " + command);
else {
System.out.println("Failed to execute the following command: " + command + " due to the following error(s):");
try (final BufferedReader b = new BufferedReader(new InputStreamReader(p.getErrorStream()))) {
String line;
if ((line = b.readLine()) != null)
System.out.println(line);
} catch (final IOException e) {
e.printStackTrace();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
Isn't Process.getErrorStream what you want?

Categories