Not able to execute an exe file from java using ProcessBuilder - java

I am making a project to run C, C++ and Java, from within Java code itself. It works absolutely fine for Java, and the problem is faced when compiling and executing C and C++ files.
I got my compilation right with this code and I can get the executable file generated in my specified path. But now when I run the executable binary from ProcessBuilder I get an error saying that 'file was not found'. Please see to the code and tell me what is going wrong and where??
public void processCode(String path,String lang)throws IOException
{
String cmd="",s=null,out=null,file="";
totalTime=0;
ProcessBuilder process=new ProcessBuilder();
process.directory(new File(path));
if(lang.equals("c")||lang.equals("cpp"))
{
cmd=threadNum+".exe";
process.command(cmd);
}
else if(lang.equals("java"))
{
cmd="java";
file="Main"+threadNum;
process.command(new String[]{cmd,file});
}
process.redirectInput(new File(PATH+"Input\\" + prob + ".txt"));
process.redirectOutput(new File(PATH+"Output.txt"));
Process p=process.start();
long start=System.currentTimeMillis();
while (true)
{
try{
if(p.exitValue()==0)
{
totalTime=(int)(System.currentTimeMillis()-start);
break;
}
}
catch (Exception e)
{
}
if(System.currentTimeMillis()-start>2000)
{
res=1;
p.destroy();
break;
}
}
if(res!=1)
{
compareFile();
}
}
The method is called from here
And the error generated is :
Exception in thread "main" java.io.IOException: Cannot run program "19.exe" (in directory "C:\wamp\www\usercodes\lokesh"): CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
at Contest.processCode(Main.java:202)
at Contest.compileCode(Main.java:180)
at Contest.makeFile(Main.java:157)
at Contest.main(Main.java:53)
at Main.main(Main.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(ProcessImpl.java:188)
at java.lang.ProcessImpl.start(ProcessImpl.java:132)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1021)
... 10 more

Setting the directory of a ProcessBuilder does not have any effect on where the system will look for the executable when it tries to start a process. It merely sets the current working directory of the newly-created process to this directory, should it be able to launch a process successfully. Your program 19.exe may well exist in C:\wamp\www\usercodes\lokesh, but unless this folder is on the PATH, the system will not be able to start your process.
Try running the process using the full path of the executable instead of just 19.exe.
It does have to be said that the error message is somewhat misleading. It says that it couldn't find your executable, and then it says 'in directory ...', which implies that that was where it was looking for it.

Related

default directory must be absolute

My code calls the methods in the log4j package:
org.apache.log4j.PropertyConfigurator.configure("log4j.properties")
There is no problem running on Windows system and Linux virtual machine. However, when running on a Linux virtual machine provided by the company, the following error occurs, as following picture shows:
Where do I start to resolve it?
Supplement:
this is my code:
public static void main(String[] args) {
PropertyConfigurator.configure(configDir + File.separator + "log4j.properties");
if(log.isDebugEnabled()) {
log.debug("load completeļ¼š" + configDir + File.separator + "log4j.properties");
}
}
The first line of execution reports an error, error is:
Exception in thread "main" java.lang.ExceptionInInitializerError
...
at org.apache.log4j.PropertyConfigurator.configure(PropertyConfigurator.java:315)
at com.dcits.provider.BaffleProvider.main(BaffleProvider.java:29)
Caused by: java.lang.RuntimeException: default directory must be absolute
...
The default FileSystem can not be constructed when the user directory system property (i.e "user.dir"), is NOT an absolute path.
Executing this code in Java 8 on both Windows and AIX generates runtime exceptions similar to that seen by the original poster.
public class RelativeUserDir
{
public static void main(String[] args)
{
// Set the "user.dir" property to the "current directory" relative path
System.setProperty("user.dir", ".");
FileSystems.getDefault();
}
}
Windows:
Exception in thread "main" java.lang.AssertionError: Default directory is not an absolute path
at sun.nio.fs.WindowsFileSystem.<init>(WindowsFileSystem.java:61)
at sun.nio.fs.WindowsFileSystemProvider.<init>(WindowsFileSystemProvider.java:53)
at sun.nio.fs.DefaultFileSystemProvider.create(DefaultFileSystemProvider.java:36)
at java.nio.file.FileSystems$DefaultFileSystemHolder.getDefaultProvider(FileSystems.java:108)
at java.nio.file.FileSystems$DefaultFileSystemHolder.access$000(FileSystems.java:89)
at java.nio.file.FileSystems$DefaultFileSystemHolder$1.run(FileSystems.java:98)
at java.nio.file.FileSystems$DefaultFileSystemHolder$1.run(FileSystems.java:96)
at java.security.AccessController.doPrivileged(Native Method)
at java.nio.file.FileSystems$DefaultFileSystemHolder.defaultFileSystem(FileSystems.java:96)
at java.nio.file.FileSystems$DefaultFileSystemHolder.<clinit>(FileSystems.java:90)
at java.nio.file.FileSystems.getDefault(FileSystems.java:176)
at RelativeUserDir.main(RelativeUserDir.java:12)
AIX:
Exception in thread "main" java.lang.ExceptionInInitializerError
at java.lang.J9VMInternals.ensureError(J9VMInternals.java:146)
at java.lang.J9VMInternals.recordInitializationFailure(J9VMInternals.java:135)
at java.nio.file.FileSystems.getDefault(FileSystems.java:187)
at RelativeUserDir.main(RelativeUserDir.java:10)
Caused by: java.lang.RuntimeException: default directory must be absolute
at sun.nio.fs.UnixFileSystem.<init>(UnixFileSystem.java:67)
at sun.nio.fs.AixFileSystem.<init>(AixFileSystem.java:55)
at sun.nio.fs.AixFileSystemProvider.newFileSystem(AixFileSystemProvider.java:62)
at sun.nio.fs.AixFileSystemProvider.newFileSystem(AixFileSystemProvider.java:55)
at sun.nio.fs.UnixFileSystemProvider.<init>(UnixFileSystemProvider.java:68)
at sun.nio.fs.AixFileSystemProvider.<init>(AixFileSystemProvider.java:57)
at java.lang.J9VMInternals.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1773)
at sun.nio.fs.DefaultFileSystemProvider.createProvider(DefaultFileSystemProvider.java:60)
at sun.nio.fs.DefaultFileSystemProvider.create(DefaultFileSystemProvider.java:78)
at java.nio.file.FileSystems$DefaultFileSystemHolder.getDefaultProvider(FileSystems.java:119)
at java.nio.file.FileSystems$DefaultFileSystemHolder.access$000(FileSystems.java:100)
at java.nio.file.FileSystems$DefaultFileSystemHolder$1.run(FileSystems.java:109)
at java.nio.file.FileSystems$DefaultFileSystemHolder$1.run(FileSystems.java:107)
at java.security.AccessController.doPrivileged(AccessController.java:638)
at java.nio.file.FileSystems$DefaultFileSystemHolder.defaultFileSystem(FileSystems.java:107)
at java.nio.file.FileSystems$DefaultFileSystemHolder.<clinit>(FileSystems.java:101)
... 2 more
When encountering this problem, especially when running under jdk1.7, notice whether the 'user.dir' environment variable has been changed or set. The problem I encountered is that the 'user.dir' was wrongly set by me

Running linux command in java

I want to run "ls" command in java and my code is-
Note:- I am using WINDOWS.
import java.io.IOException;
public class Example
{
public void fn()
{
Runtime run = Runtime.getRuntime();
Process p = null;
String cmd = "ls";
try {
p = run.exec(cmd);
p.getErrorStream();
p.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
System.out.println("ERROR.RUNNING.CMD");
} finally {
p.destroy();
}
}
public static void main(String[] args) throws IOException
{
Example sp = new Example();
sp.fn();
}
}
but I am getting following error while running this code in eclipse-
java.io.IOException: Cannot run program "ls": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at Example.fn(Example.java:12)
at Example.main(Example.java:28)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
... 6 more
Exception in thread "main" ERROR.RUNNING.CMD
java.lang.NullPointerException
at Example.fn(Example.java:23)
at Example.main(Example.java:28)
what needs to be corrected? what library, etc. should I add to execute this piece of code?
If you want to run any command from Java ensure that executable of this file is present in PATH environment variable.
Or at least you have to set working directory to /usr/bin or similar.
One more solution is to use absolute path to executable, e.g.:
Runtime.getRuntime().exec("/usr/bin/ls");
But it is bad way to specify absolute path to any file.
Why don't you use File#listFiles()?

Trying to run java program for running windows command, but program is not working

I'm trying to run windows commands by using java code, but code is not working and giving exception error.
Following is the code
import java.io.*;
public class run_command
{
public static void main(String args[])
{
try
{
String command = "start firefox";
Process process = Runtime.getRuntime().exec(command);
}
catch(IOException e){ System.out.println(e); }
}
}
And following is the exception error
java.io.IOException: Cannot run program "start firefox": Create
Process error=2, The system cannot find the file specified.
This error is occurring for every windows commands. Please suggest some solution on this.
thanks.
You have to run program start with parameter firefox:
Process process = Runtime.getRuntime().exec("start", "firefox");
start is an executable, so is firefox, but there is no such executable named start firefox.

Running a command-line operation from within Java

I built a very simple program to test running a command line operation separate of Java. That is: later I want to be able to modify this code from using "move" to any other command I can enter into the command line (including calling other, non-Java, software).
I did search and read probably two dozen answers, but they all either suggested I was trying this correctly, were irrelevent to my simple test or proposed other solutions which did not work (like using the .exec(String[]) method instead of .exec(String) - same result!).
Here is my code:
import java.io.IOException;
public class RunCommand {
private static final String PATH_OUT = "C:\\Users\\me\\Desktop\\Temp\\out\\";
private static final String FILE = "sample.txt";
private static final String PATH_IN = "C:\\Users\\me\\Desktop\\Temp\\in\\";
public static void main(String[] args) {
try {
String command = "move "+PATH_IN+FILE+" "+PATH_OUT;
System.out.println("Command: "+command);
Runtime.getRuntime().exec(command);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is what I see output when I run:
Command: move C:\Users\myingling\Desktop\CDS\Temp\in\sample.txt C:\Users\myingling\Desktop\CDS\Temp\out\
java.io.IOException: Cannot run program "move": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at RunCommand.main(RunCommand.java:13)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
... 5 more
Note that when I copy/paste the command into a command prompt window, the file moves successfully though.
What am I missing? All the other questions I've read seem to indicate this should work.
Thanks!
EDIT Works now, thanks for the help everyone! It's annoying that it's hidden the way "move" is a parameter of cmd.exe. I wish they had made it so if it worked when copy/pasted it worked when you called the .exec() method. Oh well.
The "move" command is part of the cmd.exe interpreter, and not a executable by itself.
This would work:
cmd.exe /c move file1 file2
Try this:
Runtime.getRuntime().exec("cmd.exe /c move "+PATH_IN+FILE+" "+PATH_OUT);
In Windows, unlike UNIX, move isn't a separate program. You need to involke the command processor CMD with move as an argument. Read the command line help on CMD, there's a flag you have to set.
move isn't actually a program, its a shell built-in command. Use something like:
String command = PATH_TO_SYSTEM32 + "\\cmd.exe /c move \""+PATH_IN+FILE+"\" \""+PATH_OUT + "\"";
Good practice is to always use absolute paths for external programs. (Well, good practice in this case would be to use Files.move or an equivalent instead of a platform dependent shell call)

launching terminal from application

I have created an application using Netbeans 6.9. In the application I want that when the user clicks on the run button then the terminal(Command Prompt) should open and some text should appear on the terminal. The text is actually a command. I want that the command should be executed on the terminal. Can anyone please help me.
I've written the following code....
class test extends Exception{
public static void main(String arg[]) {
String command = "cmd.exe/start cmd";
System.out.println(command);
try {
Process child = Runtime.getRuntime().exec(command);
} catch (Exception e) {
e.printStackTrace();
}
}
}
But its giving the following error...
cmd.exe/start cmd
java.io.IOException: Cannot run program "cmd.exe/start": CreateProcess error=2,
The system cannot find the file specified
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1018)
at java.lang.Runtime.exec(Runtime.java:610)
at java.lang.Runtime.exec(Runtime.java:448)
at java.lang.Runtime.exec(Runtime.java:345)
at test.main(test.java:6)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find th
e file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.(ProcessImpl.java:155)
at java.lang.ProcessImpl.start(ProcessImpl.java:99)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1010)
... 4 more
Can anyone tell me whats the problem??
-Thanks in advance
Here is a really good tutorial on Runtime and Process in Java, which covers off all the points that you are looking to do.
http://www.java-tips.org/java-se-tips/java.util/from-runtime.exec-to-processbuilder.html
Simply, you want to use Runtime to open the command window, and the Process to read and write to the output stream of that process.
The error is in your command.. "cmd.exe/start cmd"
Process prr = rt.exec("cmd /c "+i);
in this case the command you want to execute is in (String i)

Categories