I am trying to launch a bat file. The bat file is in a folder. The folder contains all the executable jar file. I tried this code to launch the bat file but unable.
ProcessBuilder pb = new ProcessBuilder( "C:\\Users\\user\\Desktop\\NetBeansProjects\\Genomic DataWarehouse Project\\biodwh.startBioDWH.bat" );
pb.redirectErrorStream(true);
Process p = pb.start();
InputStream is = p.getInputStream();
BufferedReader br = new BufferedReader( new InputStreamReader( is ) );
for ( String line = br.readLine(); line != null; line = br.readLine() )
{
System.out.println( ">" + line );
}
p.waitFor();
try use this Runtime.getRuntime().exec("cmd /c start C:\Users\user\Desktop\NetBeansProjects\Genomic DataWarehouse Project\biodwh.startBioDWH.bat");
in your .bat add the line pushd %~dp0
this will change the current drive and path to the one of the bat file.
Ok, seems I misunderstood the question.
I think you can't execute batch files directly but need to launch it using cmd.exe. Try adding cmd /c (with a space at the end) to your new ProcessBuilder line :
ProcessBuilder pb = new ProcessBuilder( "cmd /c C:\\Users\\user\\Desktop\\NetBeansProjects\\Genomic DataWarehouse Project\\biodwh.startBioDWH.bat" );
Or ou can try to execute the bat file this way :
String path="C:\\Users\\user\\Desktop\\NetBeansProjects\\Genomic DataWarehouse Project\\";
File dir = new File(path);
Process process = Runtime.getRuntime().exec("cmd /c "+path+"biodwh.startBioDWH.bat", null, dir);
Or you can make it shorter if you don't need the batch file to be executed from the folder where it resides
Process process = Runtime.getRuntime().exec("cmd /c C:\\Users\\user\\Desktop\\NetBeansProjects\\Genomic DataWarehouse Project\\biodwh.startBioDWH.bat");
Related
Hey all I am trying to change directories and then run my command with parameters.
final String path = "\\Local// Apps\\IBM\\SDP\\scmtools\\eclipse";
final String command = "scm help";
final String dosCommand = "cmd /c \"" + path + "\"" + command;
final Process process = Runtime.getRuntime().exec(dosCommand);
final InputStream in = process.getInputStream();
int ch;
while((ch = in.read()) != -1) {
System.out.print((char)ch);
}
It runs without errors but outputs nothing. However, this is what shows up after it finishes:
<terminated, exit value: 0>C:\Local Apps\IBM\SDP\jdk\bin\javaw.exe (Jul 22, 2019, 11:21:37 AM)
The expected output should be:
So am I doing this correctly?
AS suggested by Andreas
Process p = null;
ProcessBuilder pb = new ProcessBuilder("scm.exe");
pb.directory(new File("C:/Local Apps/IBM/SDP/scmtools/eclipse"));
p = pb.start();
I get the following error:
Cannot run program "scm.exe" (in directory "C:\Local Apps\IBM\SDP\scmtools\eclipse"): CreateProcess error=2, The system cannot find the file specified
You should use ProcessBuilder instead of Runtime.exec, e.g.
Process proc = new ProcessBuilder("scm.exe", "help")
.directory(new File("C:\\Local Apps\\IBM\\SDP\\scmtools\\eclipse"))
.inheritIO()
.start();
proc.waitFor(); // optional
You can also go through the command interpreter if needed, e.g. if the command is a script (.bat or .cmd file):
Process proc = new ProcessBuilder("cmd", "/c", "scm", "help")
.directory(new File("C:\\Local Apps\\IBM\\SDP\\scmtools\\eclipse"))
.inheritIO()
.start();
proc.waitFor();
The inheritIO() means that you don't need to process the commands output. It will be sent to the console, or wherever Java's own output would go.
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" };
I am trying to use ProcessBuild to run the cmd statement.
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "start");
Process p = pb.start();
However, I can only open the cmd.exe
I do not know how to add statement to the ProcessBuild so that the all the jar in the folder can run.
Usually, I open the cmd in the stanford-corenlp-full-2015-12-09 folder, and add this statement to run:
java -mx4g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer
So how to write this statement Run cmd commands through java??
I am getting errors as the statement consists "*".
How to edit the ProcessBuilder so that i can run the statement?
Thanks a lot
You could set the directory from where the command to be executed
List<String> cmds = Arrays.asList("cmd.exe", "/C", "start", "java", "-mx4g", "-cp", "*", "edu.stanford.nlp.pipeline.StanfordCoreNLPServer");
ProcessBuilder builder = new ProcessBuilder(cmds);
builder.directory(new File("D:/stanford-corenlp-full-2015-12-09"));
Process proc = builder.start();
UPDATE as requested in comments
OutputStream out = proc.getOutputStream();
new Thread(() -> {
try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out))) {
bw.write("[command here]");
bw.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}).start();
I want to unzip tgz files using 7zip utility in Windows OS. My 7zip.exe file is placed in D: drive. My unzip command is 7z e abc.tgz. This command is working through terminal but not through my java code.
Previously I tried
Runtime r=Runtime.getRuntime();
r.exec("cmd.exe d: ", null, new File("D:\\"));
Process p=r.exec("7z e abc.tgz"null,new File("D:\\"));
InputStream is=p.getInputStream();
BufferedReader br= new BufferedReader(new InputStreamReader(is));
String line=new String();
while ((line=br.readLine())!=null) System.out.println (line);
I even tried this
ProcessBuilder pb = new ProcessBuilder("cmd.exe","/c","start","cmd");
pb = pb.directory(new File("D:"));
pb.command("7z", "e", "abc.tgz");
pb.start();
Is there any different method for changing the directory through java?
You can use this snippet to change the working directory:
String[] command = unzip_your_file;
ProcessBuilder builder = new ProcessBuilder(command);
builder.directory(new File("directory_location"));
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() + "\"";