I'm trying to open the file using Runtime. This is similar to opening windows command prompt, and then executing the command.
Here is the code:
import java.io.IOException;
public class OpenFile {
public static void main(String[] args) {
String fileName = "E:\\Myfile.txt";
try {
Runtime rt = Runtime.getRuntime();
rt.exec(new String[]{"cmd.exe", "/c", "start"});
rt.exec(new String[]{fileName});
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
The command prompt is opening successfully. But the file Myfile.txt is not opening. I'm getting the below error in console:
java.io.IOException: CreateProcess: E:\Myfile.txt error=193
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(ProcessImpl.java:81)
at java.lang.ProcessImpl.start(ProcessImpl.java:30)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:451)
at java.lang.Runtime.exec(Runtime.java:591)
at java.lang.Runtime.exec(Runtime.java:464)
at OpenFile.main(OpenFile.java:10)
How to open the file successfully?
Not really an answer, but I think it's important to describe what exactly is happening in the current version of the application.
In this part of your code;
rt.exec(new String[]{"cmd.exe", "/c", "start"});
rt.exec(new String[]{fileName});
You are executing an external command. To quote the question,
similar to opening windows command prompt, and then executing the
command
What you need to realize is that whatever you've given as the string gets executed. It isn't queued or anything. Thus, re-reading your code, you are asking your program to execute 2 different commands. The first would look like;
cmd.exe /c start
Which if run on the windows command prompt executes without issues. The second "command" your program attempts to execute looks like this;
E:\Myfile.txt
Try typing that into the command prompt - it will produce an error. Probably something like "command not found". This is what the exception java.io.IOException: CreateProcess is telling you. That Java was not able to create the new process you asked it to.
Now, as for actually answering the OP, I suggest this;
rt.exec(new String[]{"cmd.exe", "/c", "start", fileName});
Which, unfortunately looks exactly like an earlier answer.
You are trying to execute fileName in Runtime object, which is wrong! Try like below:
rt.exec(new String[]{"cmd.exe", "/c", "start", fileName});
Related
I'm currently working on invoking bash program using java. The bash program output too much message and I want to redirect them to /dev/null. But I encountered a weird error No such file or directory.
Here is my demo.
public static void main(String[] args) {
try {
// Another version I've tried:
// Process p = Runtime.getRuntime().exec("echo a > /dev/null");
ProcessBuilder b = new ProcessBuilder("echo a");
// b.redirectOutput(new File("/dev/null")).redirectErrorStream(true);
b.redirectOutput(ProcessBuilder.Redirect.to(new File("/dev/null")))
.redirectErrorStream(true);
Process p = b.start();
p.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
And the error message as follows:
java.io.IOException: Cannot run program "echo a": error=2, No such file or directory
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
at test.main(test.java:12)
Caused by: java.io.IOException: error=2, No such file or directory
at java.base/java.lang.ProcessImpl.forkAndExec(Native Method)
at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:340)
at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:271)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
... 2 more
I'm using a MacBook with Catalina, and I tried java 1.8.0_231 and 1.8.0_241 from oracle. (I couldn't use higher java version because one of the dependency of my project requires java 8).
To ignore the output from the process, it's easier and more portable to use ProcessBuilder.Redirect.DISCARD than explicitly redirecting to a special file/device such as /dev/null.
b.redirectOutput(ProcessBuilder.Redirect.DISCARD)
.redirectErrorStream(true);
Forget about using Runtime.exec - that method is badly designed and hard to use safely. If you want to do input redirection with the "> /dev/null" style, you need to remember that > is a construct created by the command interpreter shell, not the operating system, and if you want to use it you must run a shell.
Runtime.getRuntime().exec(new String[] {"sh", "-c", "echo a > /dev/null"});
I have a rest service written in java on linux machine.
I'm using:
p = Runtime.getRuntime().exec(cmmnd);
or
ProcessBuilder pb = new ProcessBuilder(cmmnd).inheritIO();
p = pb.start();
p.waitFor();
I can execute commands like mkdir, touch ...
But when i try to run sh file nothing happens (for example: sudo sh /home/mydir/myfile.sh)
Is it a permission issue? How can I resolve that?
Only file execution permission is not suffice here. First run the command sudo sh /home/mydir/myfile.sh from command prompt manually and check whether work or not? Is you sodo ask for a password? Is your web service account from where you are executing the command has permission to execute as sudo? Also check whether your web application has file access permission to location (means can it execute cd /home/mydir/) /home/mydir/myfile.sh or not?
Also in your code read the output and check what is the actual error?
p.getOutputStream();
Also try with:-
ProcessBuilder pb = new ProcessBuilder("sudo sh /home/mydir/myfile.sh");
pb.redirectOutput(new File("/new_path/out.txt"));
Process p = pb.start();
try {
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
My os is MAC OS 10.11.3.
I using Spark as our IM(Instant messaging),but when the IM log out,IM give an error,said:
java.io.IOException: Cannot run program "open": error=2, No such file or directory .
But when Eclipse runs it, it worked well,and when I wrapped it a mac package and installed it and run it, click "log out" button, it throws errors.
In program, when I log out,I launch a new IM,meanwhile,I killed the old IM application.
Furthermore,in terminal,no matter what I run how many times “open -a Spark”,it just open the same IM,
The source as follows:
public boolean restartApplicationWithScript() {
String command = null;
try {
if (Spark.isMac()) {
command = "open -a " + Default.getString(Default.SHORT_NAME);
}
String commands[] = {"open", "/Applications/Spark.app"};
Runtime.getRuntime().exec(commands);
System.exit(0);
return true;
} catch (IOException e) {
Log.error("Error trying to restart application with script", e);
return false;
}
}
The exception seems to be saying that it cannot find the open command. That seems a bit odd, since it is a standard MacOS command. So I suspect that the reason that it cannot be found is that it is not on the PATH.
Try giving the absolute pathname for the open command. Running which open should tell you what it is.
If open is a shell builtin on MacOS, then you will need to create a subshell to run the command.
Thanks for all, i solved it by 2 step :
1, cmdline = { "open", "-na", "Microsoft Excel" }; this add a "n" ,otherwise,it will open the same app 。
2,chmod -R 777 youAppPath,if not do this ,the app can't issue the command
Through Jenkins - Slave setup (running in Windows), we have created a ANT job which in internally calls the below JAVA Program,
String[] command = {"cmd" , "/c", System.getProperty("user.dir")+"/Read_email/ReadEmail.vbs"};
Process p = Runtime.getRuntime().exec(command);
System.out.println("Process Completed");
The ReadEmail.vbs file never gets called or executed.
There is no error message or warning getting generated.
When I run this java program from eclipse or through Master Jenkinks, VB Scripts gets executed without any errors.
Your
String[] command = {"cmd" , "/c", System.getProperty("user.dir")+"/Read_email/ReadEmail.vbs"};
relies on the executing process to know where to find cmd.exe and who to call for a .vbs.
I used a 'fully redundant':
String[] command = {"C:/WINDOWS/system32/cmd.exe" , "/c", "C:/WINDOWS/system32/cscript.exe", "E:/trials/SoTrials/answers/21228622/java/callme.vbs"};
try {
Process p = Runtime.getRuntime().exec(command);
} catch(Exception e) {
System.out.format("%s\n", e.toString());
}
successfully from a simple commandline program. I hope this strategy works for your more complicated Jenkins setup.
I have a python compiled script (script.pyc , I haven't the .py file)that work well from my windows command prompt, and I want to execute it from my Java's application.
I tried to use runtime() method :
Runtime runtime = Runtime.getRuntime();
runtime.exec(new String[] {"C:\\toto\\tools\\script.pyc" ,"arg","arg2" });
but I get an error :
Exception in thread "main" java.io.IOException: Cannot run program "C:\Nuance\VoCon Hybrid\SDK_v4_3\tools\clctodict.pyc": CreateProcess error=193, %1 n?est pas une application Win32 valid
The script work well in my terminal ("arg" is a txt file, "arg2" is the output name, and the script does its job without any problem).
I also try to launch my script with getDesktop() :
File fie = new File("C:\\toto\\tools\\script.pyc" ,"arg","arg2");
Desktop.getDesktop().open(fie);
There is no problem, but I can't add argument, so I can just see a terminal windows opening during a few second before disappearing instantly.
I have also tried to use JPython, without success too (maybe we can't use methode "execfile" on a .pyc????)
You can do something like
Process p = Runtime.getRuntime().exec(new String[]{"python.exe" ... other args)
Then you can invoke p.waitFor() to wait for the end of the process and p.exitValue() to test if the program exited successfully.
You can also get the output stream via p.getOutputStream() to retrieve the text printed by your python script
Please refer to the class documentation for further information : http://docs.oracle.com/javase/6/docs/api/java/lang/Process.html
Just like you need a jvm to run a .class, you need a python interpreter to run a .pyc.
Try something like:
runtime.exec(new String[] {"c:\\Python26\\bin\\python.exe", "C:\\toto\\tools\\script.pyc" ,"arg","arg2" });