I am writing a java server process that in addition should run vb.exe file with parameters in windows only.
I tried to use ProcessBuilder with start function and Process with exec function but I have no error but nothing happens!
the cmd for example:
"C:\AL500\BIAFLABEL\AddToQueue.exe" "C:\AL500\BiafLabel\Templates\2.xml" -printer \\mickaelbpc\System-N
the command line definitions in the code:
String fullcmd = "\"C:\\AL500\\BIAFLABEL\\AddToQueue.exe\" \"C:\\AL500\\BiafLabel\\Templates\\2.xml\" -printer \\\\mickaelbpc\\System-N";
String fullcmd1 = "C:\\AL500\\BIAFLABEL\\AddToQueue.exe C:\\AL500\\BiafLabel\\Templates\\2.xml -printer \\\\mickaelbpc\\System-N";
String cmd1 = "C:\\AL500\\BIAFLABEL\\AddToQueue.exe";
String cmd2 = "C:\\AL500\\BiafLabel\\Templates\\2.xml";
String cmd3 = "-printer";
String cmd4 = "\\\\mickaelbpc\\System-N";
String[] command = new String[]{cmd1, cmd2, cmd3,cmd4};
Process + array:
File dir = new File("C:/workspace");
Process process = Runtime.getRuntime().exec(command, null, dir);
process.waitFor();
InputStream stdout = process.getInputStream();
InputStream stderr = process.getErrorStream();
String strData;
StringBuffer sb = new StringBuffer("");
BufferedReader brData = new BufferedReader(new
InputStreamReader(stdout));
while ((strData = brData.readLine()) != null)
{
sb = sb.append(strData).append("\r\n");
}
brData.close();
ProcessBuilder + string command with ":
ProcessBuilder pb=new ProcessBuilder(fullcmd);
pb.redirectErrorStream(true);
Process process1=pb.start();
BufferedReader inStreamReader = new BufferedReader(
new InputStreamReader(process1.getInputStream()));
String line;
while (true) {
line = inStreamReader.readLine();
if (line == null) { break; }
System.out.println(line);
ProcessBuilder + string command with no ":
File log = new File("log");
ProcessBuilder pb=new ProcessBuilder(/*command*/fullcmd1);
pb.redirectErrorStream(true);
pb.redirectOutput(Redirect.appendTo(log));
Process process1=pb.start();
BufferedReader inStreamReader = new BufferedReader(
new InputStreamReader(process1.getInputStream()));
String line;
while (true) {
line = inStreamReader.readLine();
if (line == null) { break; }
System.out.println(line);
}
after the changes I am getting this error: "java.io.IOException: Cannot run program "C:\AL500\BIAFLABEL\AddToQueue.exe C:\AL500\BiafLabel\Templates\2.xml -printer \mickaelbpc\System-N": CreateProcess error=2, The system cannot find the file specified" can you please advise?
ProcessBuilder with cmd.exe:
ProcessBuilder pb=new ProcessBuilder("cmd.exe","/c",fullcmd);
pb.redirectErrorStream(true);
Process process1=pb.start();
BufferedReader inStreamReader = new BufferedReader(
new InputStreamReader(process1.getInputStream()));
String line;
while (true) {
line = inStreamReader.readLine();
if (line == null) { break; }
System.out.println(line);
}
I did all the options and more...if it will be necessary I will add more examples
the vb exe should print a file. any idea how to run it from java process? or what is wrong with my code?
Study the error and output stream of the command. Need to redirect them and stream them in a separate thread. Or try this fronm
File log = new File("log");
pb.redirectErrorStream(true);
pb.redirectOutput(Redirect.appendTo(log));
Is the full path correct? Can you print the commad line space seperated to a file called run.cmd and run that manually and see what happens from prompt?
which directory are you starting the process from might have to be different than the one that your java program is running at? Process builder has a https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html#directory()
To know which directory your java program is using do this:
File f = new File("./");
try{
System.out.println("Start dir is :" + f.getCanonicalFile());
}catch...
https://docs.oracle.com/javase/7/docs/api/java/io/File.html#getCanonicalFile()
i do not think you do not need to add quotes, just set them in the array with actual values. but if running from a .cmd you will need to qualify params with spaces by putting quotes. best to have no spaces in the paths or params when testing.
See github.com/tgkprog/nli/blob/master/RunCmd.java if ur redirecting to log, dont get the stream again in your loop. and dont call via cmd.exe. in my example ignore the actual commmand, put ur exe and params, i just called a sh file as on ubuntu. You call with your 4 params
Related
I am able to open some program, that can get instructions from cmd to do some stuff, like opening file with certain arguments, check if it's ready, etc...
That's how I open file through Java.
final String location = "C:\\Program";
final File dir = new File(location);
String cmd = "cmd.exe /c start my-program.exe";
Process process = Runtime.getRuntime().exec(cmd, null , dir);
How do I interact with it now, send commands like "check_status" or "do_some_stuff" and get it's output to Java.
If I try this:
String [] cmd = {"cmd.exe /c start my-program.exe", "do_stuff"};
Process process = Runtime.getRuntime().exec(cmd, null , dir);
I get error: "Cannot run program "cmd.exe /c start my-program.exe.exe" (in directory "C:\Program"): CreateProcess error=2, The system cannot find the file specified"
But it does finds file when I send single String as an argument.
I understand that I can get it's output to Java this way:
java.io.InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
EDIT: Solved by using getOutputStream.
Writer w = new OutputStreamWriter(process.getOutputStream());
w.write("custom_command");
w.close();
I started Wildfly server with standalone.bat file(similar .exe file)
public static void main(String[] args) throws IOException {
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "cd D:\\Users\\turack\\Downloads\\wildfly-16.0.0.Final\\bin\\ && standalone.bat");
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while (true) {
line = bufferedReader.readLine();
if (line == null) { break; }
System.out.println(line);
}
bufferedReader.close();
}
Solved by using getOutputStream.
Writer w = new OutputStreamWriter(process.getOutputStream());
w.write("custom_command");
w.close();
Im trying to run python script via terminal but it always throws an exception: No such file or directory
StringBuffer output = new StringBuffer();
String command = "python3 Users/lounah/Documents/programming/ApplicationName/scriptName.py " + params.toString();
ProcessBuilder processBuilder = new ProcessBuilder(command);
Process process = processBuilder.start();
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
When you pass a string in ProcessBuilder it tries to run a program located in that path.
Instaed you should use a String[] with the path of your executable ( '/python3/python.exe' or 'python' or 'py') followed by the path of your script, followed by the arguments.
String[] command = {
"python3",
"Users/lounah/Documents/programming/ApplicationName/scriptName.py",
params.toString()
};
ProcessBuilder processBuilder = new ProcessBuilder(command);
I have been trying to untar a .tbz file without a lot of success in a java app. I have now decided to try and hit the command line to get the job done, and it currently doesn't through any errors but it doesn't untar the file, either. Can anyone see an issue with this?
String[] cmd = { "tar", "-xjf", "/var/tmp/filename.tbz"};
Process p =Runtime.getRuntime().exec(cmd, null);
EDIT, this works:
List<String> commands = new ArrayList<String>();
commands.add("tar");
commands.add("-xvjf");
commands.add("/var/tmp/filename.tbz");
ProcessBuilder pb = new ProcessBuilder(commands);
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String readline;
while ((readline = reader.readLine()) != null) {
System.out.println(readline);
}
What is a cd command doing there in the middle? Perhaps you meant this:
String[] cmd = { "tar", "-xjf", "/var/tmp/filename.tbz"};
If instead of the above, you really want to do this:
cd /var/tmp
tar -xjf filename.tbz
In this case you can use ProcessBuilder.
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!
I am trying to execute another file using Runtime and Process
try
{
Runtime run = Runtime.getRuntime();
Process pro = run.exec("C:\\Users\\user\\Desktop\\file.exe");
}
catch(Exception a)
{
a.printStackTrace();
}
I can enter this command in either run or cmd and am able to open the file but running it through my program it won't open. There are no errors, it just doesn't open.
To better understand what is going on (and it is actually a requirement of the Process class), you need to redirect the input and error streams of your process - and using a ProcessBuilder is the recommended way to start processes:
public static void main(String[] args) throws Exception {
ProcessBuilder pb = new ProcessBuilder("C:\\Users\\user\\Desktop\\file.exe");
runProcess(pb)
}
private static void runProcess(ProcessBuilder pb) throws IOException {
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
You must do
Process pro = run.exec("C:\\Users\\user\\Desktop\\file.exe",null,"C:\\Users\\user\\Desktop\\");
Please see Run .exe file from Java from file location
Try this way:
String []cmdarray = new String[4];
cmdarray[0] = "cmd";
cmdarray[1] = "/c";
cmdarray[2] = "start";
cmdarray[3] = "C:\\Users\\user\\Desktop\\file.exe";
Runtime.getRuntime().exec(cmdarray);
Try this one, create a batch file ,like start_file.bat.
The content like this:
cd C:\Users\user\Desktop ----- Goto this directory
C: ----- This line is very important
file.exe
Both the two approaches work well.
Runtime r = Runtime.getRuntime();
String []cmdarray = new String[4];
cmdarray[0] = "cmd";
cmdarray[1] = "/c";
cmdarray[2] = "start";
cmdarray[3] = "C:/users/desktop/start_file.bat";
r.exec(cmdarray);
And this one:
r.exec("C:/users/desktop/start_file.bat");
You can read the output from this new process.