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();
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'm creating batch file using java and Running the same..
It creates successfully and runs as well..
But after execution , the window cmd prompt doesn't close ..
And if i using
taskkill /f /im cmd.exe
it doesn't allow the complete execution.
How to close the cmd once the execution is completed..??
Any Help would be appreciated...
Runtime rt= Runtime.getRuntime();
rt.exec("cmd /c start "+serverPath+"SCA_"+projComp.getModule()+"_"+projComp.getProjectName()+"_"+projComp.getInside().get(i).getRuleSetName()+".bat", null, new File(serverPath+"MES/SERVER/MOS-ACI"));
You can create your bat file like that:
#echo off
cd //my command
exit
So you can execute your bat file like that:
public static void main(String[] args) {
try {
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "start Path-to-your-bat-file\\commandBAT.bat");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
} catch (Exception e) {
System.out.println("Exception = " + e);
}
}
I'm trying to make an ide just for fun I have no idea why but i wan't to open cmd and execute 2 commands 1 for compiling and 1 for running the compiled file.
This is how my processbuilder looks like:
ProcessBuilder process = new ProcessBuilder("cmd.exe", "/c", "start", "/k", "javac", "EkkoFunIde.java", "java", "EkkoFunIde.class");
But nothing happens no excepetions are thrown but when i only have this:
ProcessBuilder process = new ProcessBuilder("cmd.exe", "/c", "start");
It does open cmd.
I write to the file like this:
ObservableList<CharSequence> paragraph = area.getParagraphs();
Iterator<CharSequence> iter = paragraph.iterator();
try {
BufferedWriter bf = new BufferedWriter(new FileWriter(file));
while(iter.hasNext()) {
CharSequence seq = iter.next();
bf.append(seq);
bf.newLine();
}
bf.flush();
bf.close();
} catch (Exception e) {
e.printStackTrace();
}
And after the process has started i delete the file.
Your forgot to call start method (example at the top of article about ProcessBuilder class):
...
process.start();
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");