I am getting a compilation error to my code in StateMachine.java class in a Codename One project:
error: cannot find symbol
getRuntime().
symbol: method exec(String)
location: class Runtime
the full statement is;
try {
Runtime.getRuntime().exec("cmd.exe /c start dir ");
} catch (IOException e) {
System.out.println("Print this");
}
and is running fine in a plain Java project.
What am i missing?
//===============================================
ADD: ..and to
try {
Process p = Runtime.getRuntime().exec("cmd /c dir A*");
} catch (IOException e) {
System.out.println("Print this");
}
I'm also getting an compiler error saying
error: cannot find symbol
Process
symbol: class Process
location: class StateMachine
seems to be blocking the OS/backend reach-- but how, what's the "mentality" behind?
We don't support Runtime.exec and it will obviously not work on a mobile phone where you have neither cmd nor access to other processes running on the device due to process isolation. E.g. iOS maintains a private file system per process so sharing files becomes a problem.
You can use Display.getInstance().execute() to run things like the browser but obviously cmd will never work on a device regardless of the technology you choose.
Related
I am using Runtime.getRuntime().exec function to launch independent GUI Java application for subroutine task.
The code used is in simple manner:
Runtime.getRuntime().exec("java -jar /home/user/jar.jar");
Executing the code doesn't cause any process launch nor error occured! ProcessBuilder has same effect.
Checked to work correctly on Windows.
As seems, on some platforms it is ignored on system level outside Java, as JRE does not return any kind of error.
EDT: I edited the code to read stderr and stdout by parallel thread to preserve main app execution:
Process p = Runtime.getRuntime().exec(runCmd);
new DaemonFailPrint(p).start();
Thread code is:
public class DaemonFailPrint extends Thread {
private Process process;
public DaemonFailPrint(Process process) {
this.process = process;
}
#Override
public void run() {
try {
process.waitFor();
String out = "";
while (process.getInputStream().available() > 0) {
out += (char) process.getInputStream().read();
}
out += System.lineSeparator();
while (process.getInputStream().available() > 0) {
out += (char) process.getErrorStream().read();
}
JOptionPane.showMessageDialog(null, out);
} catch (InterruptedException | IOException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
}
The result is: I got empty message box straight after subprocess is "launched".
The mean is Process object seems to be created and finished in same time, but no error out exists.
The Runtime::exec() does not wait for the process to exit, so if you want to detect errors in the executed program itself, you'd need to use something like:
Process process = Runtime.getRuntime().exec("java -jar /home/user/jar.jar");
int rc = process.waitFor();
if (rc != 0)
{
System.err.println("The process failed with error: " + rc);
}
It might be, that the jar is not found or cannot be executed etc., those errors you normally see on the console, but if you have no console, the only clue might be the return code.
You might also want to check here how to capture the output console:
Capturing stdout when calling Runtime.exec
Seems that you can use process.getInputStream() to connect to the output stream of the process. So you can simply copy it to the console to see what happened.
So far so good! I found the answer recently by myself, still don't have a reason why it works this way, but I suppose it's all about internal difference of handling new processes in VM's on different platforms.
I had to edit the code this way, and now it works:
String[] runcmd = {"java","-jar","/home/user/jar.jar"};
Runtime.getRuntime().exec(runcmd);
Now it seems to work perfect. As I see it fails to process the file and execute then command with parameters given as same string while no error thrown on Java code level, it's possibly lost in VM internals.
Please, consider the following snippet which is being run from Eclipse.
Even though the external jar file does not exist no Exception is thrown and process is not null. Why is it so?
try {
Process process = Runtime.getRuntime().exec("java -jar NonExisting.jar");
if (process == null)
System.out.println("process = null");
else
System.out.println(process);
} catch (IOException e) {
System.err.println(e);
}
It prints
java.lang.ProcessImpl#1a4d139
If I run it manully from command line then there is an error:
C:\Users\workspace\Project\src>java -jar NonExisting.jar
Error: Unable to access jarfile NonExisting.jar
Process.waitFor() gives you the exit code of the spawned process, and is likely returning a non-zero (i.e. error) value. You should check this value, and collect the stdout/err at the same time (see here for more info). stderr will likely report an error.
All you're currently doing is confirming that the process has been invoked. The process then tries/fails to load the jar file, and that's when it exists and reports an error.
The process was created and finished. You should check the return value of the Process object. An exception will be thrown if there is a problem with the creation of the new process, so here you don't get an exception.
Whoa, this is quite ugly :-) Why dont you start the Main Methd of the jar in a new thread? Well you should check the exit status of the process:
http://en.wikipedia.org/wiki/Exit_status
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Process.htm
You are basically forking the process so you cannot get exceptions or anything java specific from this, you need to deal with the new process, like any other OS specific app.
I want to call a c++ executable from a java program. But after I call it, nothing happens. Then after I close the program, there an error window appears, which says abnormal program termination.
The code looks like this :
try {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("discretize.exe");
} catch (Exception exc) {/*handle exception*/
exc.printStackTrace();
}
and the windows error that appears look like this :
http://dc532.4shared.com/img/8e2-xhaG/debug.PNG
Finally I found the answer.
The problem was the command prompt didn't show up. So after searching google, I found a tip that suggested I simply put:
cmd /c start
before the path of the file. So I changed my code to look like this:
Process myProcess = Runtime.getRuntime().exec("cmd /c start D:\A_TA\KODINGAN\TA\src\discretize.exe");
.. and voila, the command prompt shows!
I would try doing this below as found from this site: http://www.boards.ie/vbulletin/showthread.php?t=218960
Example:
Process myProcess = Runtime.getRuntime().exec("path to exe");
I have a java program which is a compiler and executor for Jasper Reports and is called via shell script on our reports server.
I just fixed a bug caused by a missing dependancy, but it took me a while to figure out what was going wrong. Normally, problems caused by the compile process are captured, recorded to a log file and emailed to the relevant person. As this was a NoClassDefFoundError, it basically exited the program and failed in a silent manner from the users perspective.
Is there any way for me to capture errors like this one so that they can also be emailed away? I have the authority to modify the executing shell script.
Typically errors are not caught by application code and are thrown to JVM level where they are printed to STDERR. So, your way to track this error is to redirect STDERR to file:
java -cp YourMain 1>stdout.log 2>stderr.log
You can also put both STDOUT and STDERR together:
java -cp YourMain 1>&2 2>wholelog.log
There is a lot of reference about stream redirection in web. You can take a look there if my examples do not satisfy you. And it a depends on your OS.
Just can catch the error i.e.
try {
numericDefinition = new net.sf.cb2xml.def.BasicNumericDefinition(
binName, binarySizes, SynchronizeAt, usePositive, floatSynchronize, doubleSynchronize
);
} catch (NoClassDefFoundError e) {
System.out.println("Class Not Found: " + e.getMessage());
}
You do need to be very careful of your coding though, it is easy to get NoClassDefFoundError thrown at class initialisation time and not get into to the try .. catch block.
The NoClassDefFoundError will be thrown the first time a class is refereneced which could be when could when a class uses a class which uses a class which uses a class ... which uses a class that references a class that does not exist.
The following may fail with NoClassDefFoundError at class initialization because of the import.
import net.sf.cb2xml.def.BasicNumericDefinition; // could cause the NoClassDefFoundError
...........
try {
numericDefinition = new BasicNumericDefinition(
binName, binarySizes, SynchronizeAt, usePositive, floatSynchronize, doubleSynchronize
);
} catch (NoClassDefFoundError e) {
System.out.println("Class Not Found: " + e.getMessage());
}
I'm currently writing a Java program that can open .exe programs on my PC, like MS Word for example.
I am having a problem though, because Runtime.getRuntime().exec() will only successfully open certain programs. I have used the exact same code for all the programs, but regardless, some programs won't open.
Here is my code for a program I downloaded, Picasa 3:
class picasaHandler implements ActionListener
{
public void actionPerformed(ActionEvent r)
{
try
{
Runtime.getRuntime().exec("cmd /c start Picasa3.exe");
}
catch (IOException t)
{
JOptionPane.showMessageDialog(null,
"Sorry, could not find Picasa 3");
}
}
}
So my question is, why won't Runtime.getRuntime().exec() run all the programs I use it on, and how do I run programs like Picasa 3, that I cannot run at this moment with this method.
I'm guessing that Picasa3.exe is not on your %PATH% anywhere so it doesn't know how to load it. Have you tried specifying the full path to Picasa3.exe?
Runtime.getRuntime().exec("cmd /c \"c:\\program files (x86)\\Google\\Picasa3\\Picasa3.exe\"")
File file=new File("picassa3");
String filename=file.getAbsolutePath(file);
try
{
Runtime.getRuntime().exec(filename);
}
catch (IOException t)
{
JOptionPane.showMessageDialog(null,
"Sorry, could not find the file");
}
Runtime's exec can only start applications that are on the Windows path. Some programs are automatically on the path, while others, like Picasa, is not.
The only work-around for this is to determine the correct path and then launch that application.
This might work for you.
If you want to run a certain program using Runtime.exec(), just add it's installation path to path variable in your System Variables. To find it's installation path, simply right click on it's shortcut and select "Find Target". Then concat that entire address at the end of your path Variable.