Im trying to run a bat from C:/abc/def/coolBat.bat but my java workspace is in D:/
I've tried with :
String cmd = "cmd /c /start C:/abc/def/coolBat.bat";
Runtime.getRuntime().exec(cmd);
But didn't work, so I tried this
String[] command = { "cmd.exe", "/C", "C:/abc/def/coolBat.bat" };
Runtime.getRuntime().exec(cmd);
didnt work either. Tried this too
Executor exec = new DefaultExecutor();
exec.setWorkingDirectory(new File("C:/abc/def"));
CommandLine cl = new CommandLine("coolBat.bat");
int exitvalue = exec.execute(cl);
Says it cant find the file.
Tried something like this too:
Runtime.getRuntime().exec("cmd cd /d C:/abc/def/ && coolBat.bat");
And nothing. The weird thing is that this command:
cd /d C:/abc/def/ && coolBat.bat
Works when i do it in cmd. Its worth saying that the bat file copies some files to another directory, all inside C:/
EDITED N°1
CD C:\abc\def\MN
copy almn + ctmn + bamn C:\abc\def\mn_sf.txt
CD C:\abc\def\ME
copy alme + ctme + bame C:\abc\def\me_sf.txt
CD C:\abc\def\
if exist MN.txt del MN.txt
if exist ME.txt del ME.txt
if exist JUZ.txt del JUZ.txt
if exist FUNC.txt del FUNC.txt
if exist AHO.txt del AHO.txt
CD C:\
Allow MS Windows to use the associated application to run your batch file (or any other application):
Required Imports:
import java.awt.Desktop;
Here is code you can try:
String filePath = "C:/abc/def/coolBat.bat";
if (Desktop.isDesktopSupported()) {
try {
File myFile = new File(filePath);
Desktop.getDesktop().open(myFile);
}
catch (IOException | IllegalArgumentException ex) {
System.err.println("Either there is no application found "
+ "which is associatd with\nthe file you want to work with or the "
+ "file doesn't exist!\n\n" + filePath);
}
}
Well I finally got it to work, just had to change my workspace to C:/
Apparently the problem was that it couldn't change from D:/ to C:/ to execute. I ran the same commands I tried before and there was no problem.
Guess the question remains, why it couldn't change from D:/ to C:/ when running commands from Java.
Thanks to everyone for the help
The Java version could work as:
String[] command = {"cmd.exe", "/C", "Start", "/D", "c:\\abc\\def", "c:\\abc\\def\\coolBat.bat"};
Process process = Runtime.getRuntime().exec(command);
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((line = errReader.readLine()) != null) {
System.out.println(line);
}
System.out.flush();
int retCode = process.waitFor();
System.out.println("Return code: " + retCode);
Try this:
String[] command = { "cmd.exe", "/C", "C: && C:/abc/def/coolBat.bat" };
Related
I started a project in Processing and then found that I needed more functionality. I had the following function that worked fine in Processing but now in the java environment I am getting an error.
Function:
void camSummary() {
System.out.format("Cam summary");
String commandToRun = "./camSummary.sh";
File workingDir = new File(main.path);
try {
Process p = Runtime.getRuntime().exec(commandToRun, null, workingDir);
int i = p.waitFor();
if (i==0) {
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ( (returnedValues = stdInput.readLine ()) != null) {
System.out.format(returnedValues);
}
}
}
catch(Throwable t) {
System.out.format("error: " + t + "\n");
}
}
Error:
Cannot run program "camSummary.sh" (in directory
"/Users/lorenzimmer/Documents/RC/CamSoft/ "): error=2, No such file or
directory
I've found that there have been some very slight differences from processing to java. I'm wondering if this function just needs to be tweaked slightly to run properly.
Any help would be greatly appreciated.
Loren
Runtime.exec does not invoke a shell, so you have to explicitly invoke one (bash, sh, etc)
Try this:
Change String commandToRun = "./camSummary.sh";
to
String[] commandToRun = {"bash", "-c", "/path/to/camSummary.sh"};
or
String[] commandToRun = {"sh", "/path/to/camSummary.sh"};
Then change
Process p = Runtime.getRuntime().exec(commandToRun, null, workingDir);
to
Process p = Runtime.getRuntime().exec(commandToRun);
In one line: Process p = Runtime.getRuntime().exec(new String[] {"bash", "-c", "/path/to/script"});
public void VerifyFiles(File dir) throws IOException{
File[] files = dir.listFiles();
for (File file : files) {
//Check if directory
if (file.isDirectory()) {
//Recursively call file list function on the new directory
VerifyFiles(file);
} else {
try {
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", "cd \" C:\\Users\\e843778\\Documents\\NetBeansProjects\\EncryptedFiles\" && C:\\Program Files\\PGP Corporation\\PGP Desktop");
builder.redirectErrorStream(true);
Process p = builder.start();
Runtime rt = Runtime.getRuntime();
String query2 = "cmd /c pgpnetshare -v " + "\"" + file + "\"";
Process proc = rt.exec(query2);
proc.waitFor();
System.out.println("Executing for: " + file);
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
String s1 ="";
while ((line = in.readLine()) != null)
{
System.out.println(line);
if(line.contains("All files and folders are encrypted"))
s1+=line;
}
System.out.println(s1);
}
I have to run a pgpnetshare command for all the files in a given directory using command prompt. For that, first i need to change my current directory to other directory. But i was not able to change the directory with the below code. I have checked all the previous answered questions in Stackoverflow.com. But none of them helped me.Please verify the code and please let me know if it needs any corrections. Thanks in advance!!.
That should work:
Process process=Runtime.getRuntime().exec(query2,
null, new File("directory path"));
From the documentation:
Process exec(String[] cmdarray, String[] envp, File dir)
Executes the specified command and arguments in a separate process with the specified environment and working directory.
You can always create a .bat file and execute that instead.
you should use using file.getAbsolutePath()
like
String query2 = "cmd /c pgpnetshare -v " + "\"" + file.getAbsolutePath() + "\"";
So I want to execute sh script from java
Code:
String command = "/__data/1.sh";
ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", command);
Process p = null;
try {
p = pb.start();
} catch (IOException e) {
System.out.println("Could not execute script");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
try {
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(command + " says: " + line);
}
} catch (IOException e) {
System.out.println("Error reading response");
}
1.sh:
echo Hello
mkdir QWE
echo Hello2
What I got:
/__data/1.sh says: Hello
/__data/1.sh says: Hello2
Mkdir takes no effect
1.sh chmodded to 777
What's the problem?
UPD: oh, my fault, forgot the line, now edited. But the main question is why other commands do not work. Yea, like mkdir.
When I call /bin/bash -c /__data/1.sh from console it works propertly
UPD: oh, it seems, mkdir doesn't work propertly because I did not set full path. Sorry. Solved
You're missing + line at the end of println. That should at least get rid of some of the confusion. Not sure why mkdir isn't working though.
A small issue while trying to execute R package using Java.
Runtime run = Runtime.getRuntime();
Process pr = null;
String line = null;
BufferedReader input = null;
try {
pr = run.exec("cmd /c R");
input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
while((line = input.readLine()) != null) {
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Exited with error code " + exitVal);
} catch (Exception e) {
e.printStackTrace();
}
I'm getting Exited with error code 2. Could any one help me?
On Windows exit code 2 generally means "file not found". Check in which folder are you are running the "cmd /c R". You can test this by creating a new file and then search your computer where it was created, or by executing the dir.exe command and then checking the result.
I suggest you specify the full path of the package R including extension. This is because when run from cmd , it assumes that the file is in the current working directory however, when run from java, the path has to be specified
Your code should look something like this:
pr = run.exec("cmd /c C:/test/R.exe");
Note: it doesn't have to be a .exe file I just put it as an example. for other files just change exe to the file's extension.
Hope this helped.
I'm using this code to make my Java program open a (visible) CMD window:
try {
String line;
Process p = Runtime.getRuntime().exec("cmd /C start \"Render\" \"" + myPath + "\\punchRender.cmd\"");
BufferedReader input =
new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
jLabel7.setText(line);
}
input.close();
} catch (Exception err) {
err.printStackTrace();
}
and I've been trying to do the same thing with the OSX terminal, this is where I'm at right now:
try {
String line;
Process p = Runtime.getRuntime().exec("sh " + myPath + "/punchRender.sh");
BufferedReader input =
new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
jLabel7.setText(line);
}
input.close();
} catch (Exception err) {
err.printStackTrace();
}
So far, no luck :( Any suggestions? The .sh file isn't even running...
I would just make sure your shell script has the execute bits on and just pass in the shell script file name.
Process p = Runtime.getRuntime().exec(myPath + "/punchRender.sh")
Edit:
I don't know Java specifically if there is anyway to set file permissions for Unix/Linux with it to set the eXecute bit or how to escape quotes. But It would be something like this:
Process chmod = Runtime.getRuntime().exec("chmod u+x \"" + myPath + "/punchRenderer.sh\"")
This should work. Not only running the script, but opening a terminal also:
Process p = Runtime.getRuntime().exec("open -a /Applications/Utilities/Terminal.app \"" + myPath + " /punchRender.sh\"");
If you want a new visible Terminal window, you can't run the shell directly. You need to start Terminal and then run a .command file, not a shell script. I'm not sure how hard it would be to connect the stdout of that command to your Java process. You might have to figure out some other way of getting the output into the terminal.
By the way, I tried your code in a class on my own Mac at home, and it ran a .sh file just fine. I was running the java class from the command line. Maybe sh just isn't in your PATH.
I assume you've checked that the .sh file is executable, haven't you?
Can I suggest you capture the standard error as well as the standard output, and dump that. That should give you some idea as to what's going on (it's good practise generally).
You may need to gather standard output and standard error in different threads to avoid blocking issues. See here for a StreamGobbler