Running linux command in java - 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()?

Related

Java syntax escapting symbols?

I need to process a command in cmd and the command looks like this:
"c:\Program Files (x86)\HMA! Pro VPN\bin\HMA! Pro VPN.exe" -changeip
But I can't really add the " because I will get errors..
Is there a way to do that? What i've tried causes errors:
cmd.exec(""c:/Program Files (x86)/HMA! Pro VPN/bin/HMA! Pro VPN.exe" -reconnect");
How can I escape that character so it works?
Exception in thread "Thread-1" java.lang.IllegalArgumentException: Executable name has embedded quote, split the arguments
at java.lang.ProcessImpl.isQuoted(Unknown Source)
at java.lang.ProcessImpl.getExecutablePath(Unknown Source)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
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 HMACommand.reconnect(HMACommand.java:15)
You can escape characters using a backslash (\).
In your case the result will be this:
String test = "\"c:\\Program Files (x86)\\HMA! Pro VPN\\bin\\HMA! Pro VPN.exe\" -changeip";
You'll also have to escape the backslashes themselves.
Referring to your edit:
This answer explains why you get the error you're getting.
From the cited source:
On Windows platform, the decoding of command strings specified to Runtime.exec(String), Runtime.exec(String,String[]) and Runtime.exec(String,String[],File) methods, has been improved to follow the specification more closely. This may cause problems for applications that are using one or more of these methods with commands that contain spaces in the program name, or are invoking these methods with commands that are not quoted correctly.
Instead, use a ProcessBuilder.
You could use a ProcessBuilder like so
String[] cmdLine = {
"c:/Program Files (x86)/HMA! Pro VPN/bin/HMA! Pro VPN.exe",
"-changeip"
};
try {
ProcessBuilder pb = new ProcessBuilder(cmdLine);
Process p = pb.start();
p.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}

JAVA - path issue (works in eclipse, not in cmd)

Why the following iniciation works in eclipse:
private static MaxentTagger maxentTagger = new MaxentTagger("c:\\DP\\lemma\\models\\english-left3words-distsim.tagger");
but in command line it throws:
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoa
der.java:58)
Caused by: java.lang.ExceptionInInitializerError
at dp.beans.MySearch.<init>(MySearch.java:122)
at dp.runable.Main.main(Main.java:25)
... 5 more
Caused by: java.lang.IllegalArgumentException: name
at sun.misc.URLClassPath$Loader.findResource(Unknown Source)
at sun.misc.URLClassPath.findResource(Unknown Source)
at java.net.URLClassLoader$2.run(Unknown Source)
at java.net.URLClassLoader$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findResource(Unknown Source)
at java.lang.ClassLoader.getResource(Unknown Source)
at java.net.URLClassLoader.getResourceAsStream(Unknown Source)
at edu.stanford.nlp.io.IOUtils.findStreamInClasspathOrFileSystem(IOUtils.java:370)
at edu.stanford.nlp.io.IOUtils.getInputStreamFromURLOrClasspathOrFileSystem(IOUtils.java:399)
at edu.stanford.nlp.tagger.maxent.MaxentTagger.readModelAndInit(MaxentTagger.java:646)
at edu.stanford.nlp.tagger.maxent.MaxentTagger.<init>(MaxentTagger.java:284)
at edu.stanford.nlp.tagger.maxent.MaxentTagger.<init>(MaxentTagger.java:248)
at dp.data.Settings.<clinit>(Settings.java:80)
... 7 more
Settings.java:80 corresponding with MaxentTagger iniciation..
Is there a different way to declare windows path, which works in both, eclipse and cmd?
update (the findStreamInClasspathOrFileSystem method):
private static InputStream [More ...] findStreamInClasspathOrFileSystem(String name) throws FileNotFoundException
{
String path = null;
if (name.startsWith("/")) {
path = name.substring(1);
}
// - even though this may look like a regular file, it may be a path inside a jar in the CLASSPATH
// - check for this first. This takes precedence over the file system.
InputStream is = null;
if (path != null) {
is = IOUtils.class.getClassLoader().getResourceAsStream(path);
// windows File.separator is \, but getting resources only works with /
if (is == null) {
is = IOUtils.class.getClassLoader().getResourceAsStream(path.replaceAll("\\\\", "/"));
}
}
// if not found in the CLASSPATH, load from the file system
if (is == null) is = new FileInputStream(name);
return is;
}
update: no matter if i change the path to:
"c:/DP/lemma/models/english-left3words-distsim.tagger");
"c:\\\\DP\\\\lemma\\\\models\\\\english-left3words-distsim.tagger");
its behaviour is still the same (works in eclipce, not in cmd)
Your code seems to load a resource from the classath, using the ClassLoader. The path should take the following form:
com/yourcompany/yourapp/english-left3words-distsim.tagger
where com.yourcompany.yourapp is the package where the file resides.
See http://docs.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html#getResource%28java.lang.String%29
EDIT:
The code of IOUtils.getInputStreamFromURLOrClasspathOrFileSystem() passes two badly formatted paths (c:\... and c:/...) to ClassLoader.getResourceAsStream(), and expects this method to simply return null instead of throwing an exception, which is wrong. I would simply decide where I want to load the resource rom: either the classpath (and thus use ClassLosader.getResourceAsStream()) or the file system (and thus use new FileInputStream()).

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)

Not able to execute an exe file from java using ProcessBuilder

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.

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