Java open cmd and execute command using ProcessBuilder - java

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();

Related

ProcessBuilder doesn't recognise embedded command

I have a method
final ProcessBuilder processBuilder = new ProcessBuilder(this.cmd);
processBuilder.redirectErrorStream(true);
try {
final Process process = processBuilder.start();
try (final BufferedReader reader =
new BufferedReader(
new InputStreamReader(
process.getInputStream()
)
)
) {
while (reader.ready()) {
System.out.println(reader.readLine());
}
process.waitFor(this.timeOut, TimeUnit.SECONDS);
}
} catch (final Exception exc) {
throw new IllegalStateException("Terminal command execution exception", exc);
}
This method takes cmd(array of strings) from Constructor and then executes it. This is the value of cmd
new String[]{"cat","$(cat /home/Downloads/tmp/aqnYtUSVFp.txt)",">","/home/Downloads/hello.ts"}
So the whole command is looks like this cat $(cat home/Downloads/tmp/aqnYtUSVFp.txt) > /home/Downloads/hello.ts
It works fine if I run it within terminal , but ProcessBuilder shows me the following error
cat: '$(cat /home/Downloads/aqnYtUSVFp.txt)': No such file or directory
cat: '>': No such file or directory
cat: /home/Downloads/hello.ts: No such file or directory
What did I miss . Why ProccBuilder doesn't recognize this command ?

Run bat file from different disk with java

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" };

Run cmd commands through java processBuilder

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();

Java ProcessBuilder executing command has no output

I am using ProcessBuilder to execute git command inside my java application. The output string is correct when the command is "git status" or "git branch", however the output was empty when the command is "git clone". I wonder how can I get the output string of "git clone". Thanks in advance.
try {
ProcessBuilder pb = new ProcessBuilder("git", "clone", "address");
Process pr = pb.start();
BufferedReader buf = new BufferReader(new InputStreamReader(pr.getInputStream()));
String cmdLine = "";
while ((cmdLine = buf.readLine()) != null) {
System.out.println(cmdLine);
}
} catch (Exception e) {
}

Unable to close cmd console automatically after excution from java

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);
}
}

Categories

Resources