When I execute a shell script using the method below, my "if (p.exitValue() != 0)" code runs TWICE when it is successful... anyone know why? Also, when the shell script fails, the else code runs once, and then the success code runs again anyway. What am I doing wrong?
void exec(String commander){
Process p = null;
try {
p = Runtime.getRuntime().exec(commander);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StreamGobbler errorGobbler = new
StreamGobbler(p.getErrorStream(), "ERROR");
// any output?
StreamGobbler outputGobbler = new
StreamGobbler(p.getInputStream(), "OUTPUT");
// kick them off
errorGobbler.start();
outputGobbler.start();
// any error???
int exitVal = 1;
try {
exitVal = p.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("ExitValue: " + exitVal);
if (p.exitValue() != 0)
{
//SUCCESS Code RUNS TWICE
}
else {
//FAILURE Code Runs Once, then Success Code Runs anyway!! WHY?
}
}
Maybe your void exec(String commander) is being called twice too. Did you check that?
Related
I have created a java gui which takes values from the user send it to python file for processing and then displays the output from the python file onto the java gui. This is working perfectly on eclipse but when i exported it into a jar file the output is not displayed. I've seen a bunch of other questions like this but they do not give a solution that would help me.
This is how i connect my python script to java.
public void connection(String name)
{
ProcessBuilder pb= new ProcessBuilder("python","recomold.py","--movie_name",name);
///System.out.println("running file");
Process process = null;
try {
process = pb.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int err = 0;
try {
err = process.waitFor();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// System.out.println("any errors?"+(err==0 ? "no" : "yes"));
/* try {
System.out.println("python output "+ output(process.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
try {
matches.setText(output(process.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String output(InputStream inputStream) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try{
br= new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
//descp.setText("<html><br/><html>");
//sb.append("\n");
}
}
finally
{
br.close();
}
return sb.toString();
}
I am trying to run some servers from a bot, but I can't get it run my screen and host the server. I've tried debugging and getting some kind of code to debug, but I come up with nothing. Maybe it's something in my syntax?
These are the value you can run in: name = factorio, path = /opt/factorio/bin/x64/factorio, args = --start-server map.zip
Together makes:
screen -dmS factorio -m bash -c "/opt/factorio/bin/x64/factorio --start-server map.zip"
public boolean run() {
try {
System.out.println("screen -dmS "+serverName+" -m bash -c \""+path+" "+args+"\"");
Process proc = rt.exec("screen -dmS "+serverName+" -m bash -c \""+path+" "+args+"\"");
BufferedReader read = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String str = null;
while ( (str = read.readLine()) != null)
System.out.println(str);
try {
proc.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Exit value: "+proc.exitValue());
this.setStatus(ONLINE);
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
I am running an executeable from java(1.8) on Windows 7
Process process = null;
try {
process = new ProcessBuilder("D:\\Demo\\pvaroptimizer\\bin\\pvaroptimizer.exe","-p",importantInfo[0],"D:\\Demo\\pvaroptimizer\\bin\\New structure.pvz").start();
while(process.isAlive())
{
Thread.sleep(5000);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The exeucteable runs properly but the exe which normally takes 3 Gb space in memory(checked in the taskbar) when run from commmand prompt, now reaches a maximum of 30 mb space only, hence slowing down the execution. Can someone please help me to know about this limitation.
The proble is that pvaroptimizer.exe write to output, but output buffer have limited size. When buffer is full pvaroptimizer.exe blocks until there is free space in buffer.
Next code should solve this problem.
Process process = null;
try {
ProcessBuilder builder = new ProcessBuilder("D:\\Demo\\pvaroptimizer\\bin\\pvaroptimizer.exe", "-p", importantInfo[0], "D:\\Demo\\pvaroptimizer\\bin\\New structure.pvz");
builder.redirectErrorStream(true);
process = builder.start();
InputStream stream = process.getInputStream();
while(stream.read()!=-1){}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I've found this topic, but the code doesn't work for me... Return Windows cmd text from Java?
After pressing a button I want to execute a batch-file, for testing purposes it's just the ipconfig-command.
The cmd-output should be written into a JTextFiled, but all I get is no text...
Here the code for writing it into the JTextField:
btnLock.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String g = "";
try {
Runtime.getRuntime().exec(new String[] {"ipconfig", g});
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Process p = null;
try {
p = Runtime.getRuntime().exec(new String[] {"ipconfig", g});
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStream s = p.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(s));
String temp;
try {
while ((temp = in.readLine()) != null)
{
System.out.println(temp);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnLock.setBounds(10, 68, 89, 23);
contentPane.add(btnLock);
So what do I do wrong?
It's my first project with cmd-input, so please don't get mad cause of silly mistakes I made. ;)
Thx
Try the exec command that just takes a String parameter. The following test code worked on my system (though I was only printing to console, not to textfield):
BufferedReader in = null;
try{
Process p = Runtime.getRuntime().exec("ipconfig");
InputStream s = p.getInputStream();
in = new BufferedReader(new InputStreamReader(s));
String temp;
while ((temp = in.readLine()) != null) {
System.out.println(temp);
}
} catch (Exception e){
e.printStackTrace();
} finally {
if (in != null) in.close();
}
Also your code in the original post is also using a System.out.println. As far as I'm aware, you can't print to a JTextField using System.out.println.... You'd have to use the setText method.
If I run
ipconfig ""
I get
** Error: unrecognized or incomplete command line.**
You can only run from Java, commands which work on the command line.
BTW: If you are looking for errors, you need to read the error stream.
I would Runtime.getRuntime().exec(new String[] {"ipconfig > temp.txt"}); and then just read it as a text file using a BufferedReader.
I hope this helps.
How can I mount a .dmg file through java code under OS X?
This will work (but only on OS X):
try {
String[] command = {"/usr/bin/hdiutil", "attach", "/Users/path/to/your.dmg"};
String sendback = "";
Process proc = Runtime.getRuntime().exec(command);
InputStream istr = proc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(istr));
String str;
while ((str = br.readLine()) != null) {
sendback = sendback + str;
}
int resultCode = proc.waitFor();
br.close();
if (resultCode != 0) {
throw new Exception("failed to open system profiler");
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DMGs are not executables, are apple diskimages
reference is here
thus you can't "run" it.
You can use a Process, of course. But it won't work anywhere except on a Mac.
Saying that is like asking how to run an ISO file through Java. You simply can't; it's a disk image.