ProcessBuilder doesn't recognise embedded command - java

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 ?

Related

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

Java open cmd and execute command using ProcessBuilder

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

Calling "mysqldump" with Runtime.getRuntime().exec(cmd) from Windows 7

I am trying to dump a MySQL database within my Java application the following way:
String[] command = new String[] {"cmd.exe", "/c", "C:/mysql/mysqldump.exe" --quick --lock-tables --user=\"root\" --password=\"mypwd\" mydatabase > \"C:/mydump.sql\""};
Process process = Runtime.getRuntime().exec(command);
int exitcode = process.waitFor();
The process fails with exit-code 6. I somewhere read that the operand ">" is not correctly interpreted and there was the hint to use "cmd.exe /c" as prefix. But it still doesn't work.
Any ideas?
Yes, you are right , some days ago I made class for exporting DataBase from MySQL...
You coud read output sream from console and then write to file
String[] command = new String[] {"cmd.exe", "/c", "\"C:/Program Files/MySQL/MySQL Server 5.6/bin/mysqldump.exe\" --quick --lock-tables --user=\"root\" --password=\"mypwd\" mydatabase "};
Process process = Runtime.getRuntime().exec(command);
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line); //there you can write file
}
input.close();
Best Regards
Okay here's the final solution. You need to put the "process-reader to file-writer" code into a separate thread and finally wait for the process object to be finished:
// define backup file
File fbackup = new File("C:/backup.sql");
// execute mysqldump command
String[] command = new String[] {"cmd.exe", "/c", "C:/path/to/mysqldump.exe --quick --lock-tables --user=myuser --password=mypwd mydatabase"};
final Process process = Runtime.getRuntime().exec(command);
// write process output line by line to file
if(process!=null) {
new Thread(new Runnable() {
#Override
public void run() {
try{
try(BufferedReader reader = new BufferedReader(new InputStreamReader(new DataInputStream(process.getInputStream())));
BufferedWriter writer = new BufferedWriter(new FileWriter(fbackup))) {
String line;
while((line=reader.readLine())!=null) {
writer.write(line);
writer.newLine();
}
}
} catch(Exception ex){
// handle or log exception ...
}
}
}).start();
}
if(process!=null && process.waitFor()==0) {
// success ...
} else {
// failed
}
On Linux you can directly re-direct the output of the command to a file by using ">" as usual... (and also on Mac OS X I think). So no need for the thread. Generally, please avoid white spaces in your path to the mysqldump/mysqldump.exe file!

Pass filename for command execution

I am searching files based on extension. Now for each file found, want to run a command:
Lets assume file found: C:\Home\1\1.txt. My exe exists in: C:\Home\Hello.exe
I would like to run command something like: "C:\Home\Hello.exe C:\Home\1\1.txt"
similarly for C:\Home\ABC\2.txt - "C:\Home\Hello.exe C:\Home\ABC\2.txt"
Kindly help me how to pass a searched file as an input to execute a command.
Thanks,
Kino
You can use below program as a base and then customize further as per your rqeuirement
public class ProcessBuildDemo {
public static void main(String [] args) throws IOException {
String[] command = {"CMD", "/C", "dir"}; //In place of "dir" you can append the list of file paths that you have
ProcessBuilder probuilder = new ProcessBuilder( command );
//You can set up your work directory
probuilder.directory(new File("c:\\xyzwsdemo")); //This is the folder from where the command will be executed.
Process process = probuilder.start();
//Read out dir output
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:\n",
Arrays.toString(command));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
//Wait to get exit value
try {
int exitValue = process.waitFor();
System.out.println("\n\nExit Value is " + exitValue);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Lets get you started:
Filter files using: FilenameFilter:
http://docs.oracle.com/javase/7/docs/api/java/io/FilenameFilter.html
Sample:
http://www.java-samples.com/showtutorial.php?tutorialid=384
And after you have got the files:
Use ProcessBuilder to execute:
http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html
Sample:
http://www.xyzws.com/Javafaq/how-to-run-external-programs-by-using-java-processbuilder-class/189
If you are running your app from the command line (e.g. windows cmd), and your program name is Hello.java, only thing you have to do is to put in the argument, just like you did in your example. So it looks something like:
java Hello C:\Home\1\1.txt
I did not use exe, since this is an example, and the question is tagged with "java" tag.
Your Hello.java MUST have a main method that looks like this:
public static void main(String ... args) {
}
The parameter args are the actual parameters you enter in the command line. So to get the file name, you would have to do this:
public static void main(String ... args) {
String fileName= args[0];
}
And that's it. Later on, you can do with that whatever you want, i.e. open and edit a file:
File file= new File(fileName);
//do whatever with that file.
This code will help you
public static void main(String args[]) {
String filename;
try {
Runtime rt = Runtime.getRuntime();
filename = "";//read the file na,e
Process pr = rt.exec("C:\\Home\\Hello.exe " + filename );
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Error "+exitVal);
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
}

Text file is created when running code from the terminal, but not when running it in Java

public static void main(String[] args) throws Exception {
System.setOut(new PrintStream(
new FileOutputStream("/home/main/smt/output/out.txt")));
try {
String line;
Process p = Runtime.getRuntime().exec(
"/home/main/smt/tools/moses-2010-08-13/moses/moses-cmd/src/moses " +
"-f /home/main/smt/work/model/moses.ini " +
"< /home/main/smt/work/corpus/dataset.en" );
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()) );
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}
catch (Exception e) {
// ...
}
}
the command
home/main/smt/tools/moses-2010-08-13/moses/moses-cmd/src/moses
-f /home/main/smt/work/model/moses.ini
< /home/main/smt/work/corpus/dataset.en
>/home/main/smt/output/out.txt
gets executed in terminal of Linux and out.txt is created. But in java no out.txt is created.
dataset.en is the input file. Using exe moses which is in src and moses.ini in model the content in dataset.en gets translated and saved in out.txt.
But here while running this code no out.txt is created. I removed saving output in a file from the command eventhough nothing gets displayed in the console. If i change Process p = Runtime.getRuntime().exec(ls) its working fine.
Shell can interpret the redirection and arguments. You should instead try
String[] cmd = {"/bin/ksh", "-c", "yourcommand < infile"};
Process process = Runtime.getRuntime().exec(cmd);

Categories

Resources