Not able to execute a cmd file in java - java

I have to execute a xyz.cmd file which is in a directory E:/abc. So the absolute path of the file to be executed is E:/abc/xyz.cmd. When executed, a new window is created by the file itself.
My code snippet is:-
String path = “E:\\abc”;
String cmd = path + “\\xyz.cmd”;
ProcessBuilder processBuilder = new ProcessBuilder(cmd);
processBuilder.redirectErrorStream(true);
processBuilder.directory(new File(path));
processBuilder.start();
This does not work, but gives no error or exception. But the cmd file works fine, it can be executed manually from its directory using explorer or cmd-prompt.
Tried using different versions of jdk, but in vain. I am using windows 7 OS. I do not see the process running in the Task Manager also.
Any idea what is going wrong? The same code works fine in a different computer with the same config.
===EDIT====
Can this be a security issue? Something like the user executing the program is not having enough priveleges to execute a file?

You need to call cmd.exe as first part of your process builder String in order for the command processor to be able to call the .cmd file. This is also true for .bat files, or any OS type command. For example, please look here.
Also, please look here: When Runtime.exec() won't
Edit
You state:
please understand, this is not the problem of not adding cmd.exe in the processbuilder; because of the previous commands, cmd.exe will be taken care.
I see no documentation in your posts so far that this is true, and all my experience strongly suggests otherwise.
You also state:
Can this be a security issue? Something like the user executing the program is not having enough priveleges to execute a file?
No way to know unless you capture and display the process's input stream. In fact if you don't capture this stream, you could prevent your process from functioning at all. Often we have to also capture the error stream as well, but you've combined them with
processBuilder.redirectErrorStream(true)
Please read my "When Runtime.exec() won't" link above for more on the necessity of capturing streams.

Related

Why is the jar file immediately terminated after being called using a Python script?

I'm currently programming a Python script that opens a file in an different directory that the user enters in an input box. Everything runs fine but the jar file I used for testing doesn't run or show up. I'm using the Shimeji-ee.jar in testing, and at one point its tray icon showed up but disappeared immediately.
I tried running it in command prompt(since calling the jar file using the script is similar to running a file in CMD) and discovered that it only runs as long as the CMD window is open. A few searches later, I've found a way to run files in CMD that keeps it running even after closing the CMD. I wrote it in my script, no errors, but the Shimeji nor its tray icon doesn't ever appear anymore.
I've added a line at the end of my script that is also told to be an efficient way of keeping the script running, but it doesn't work either(could be another mistake here):
while True:
keyboard.wait('q')
if keyboard.is_pressed:
sys.exit()
Here's the line of code in my script that does the calling:
subprocess.run(['D:', 'cd', PurePath(fileDirectory), 'START', '""', fileToExecute], cwd=os.getcwd(), shell=True)
The code I learnt that makes a file run in the background(similar to adding & in a Linux terminal):
START "" program
I've had thoughts that the jar file I'm using could be the problem, but I haven't found any answers for hours. Is there anything wrong with the code or am I missing something?
Update:
Code finally worked after the first answer but I received an error that seemed it read the file as a double forward slash like this:
# The network path was not found //
or
# The system could not find the file //
The solution I found was just removing the '""' part of the code, which makes the code look like this:
subprocess.run(['START', fileToExecute], cwd=PurePath(fileDirectory), shell=True)
The problem is that your code:
subprocess.run(['D:', 'cd', PurePath(fileDirectory), 'START', '""', fileToExecute], cwd=os.getcwd(), shell=True)
executes the command D: with the arguments cd somedirectory START "" fileToExecute, which changes the current drive of the shell to the D drive and then terminates.
You probably want to execute
subprocess.run(['START', '""', fileToExecute], cwd=PurePath(fileDirectory), shell=True)

Using Java code to run multiple commands with Runtime/Processbuilder

I'm trying to do something very simple here, but it isn't working.
Basically I have a program and an input file sitting at a certain directory, let's call it "programDir".
I'm writing a plugin in Eclipse that will call this program and run it on the input file.
Essentially two steps must be done: 1) cd to programDir 2) run the program by calling "idp input.txt"
I have done this manually in the cmd and it works as expected. However in Java I can't get it to work. I tried 2 approaches:
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("cmd.exe /c cd \""+programDir+"\" & \"idp input.txt\"");
Here I get the following from the errorStream: "idp output.txt" is not recognized as an intern or extern command, program or batch file
I'm not sure why. I have left out the second part of the command to ensure that I am in the correct location. When i add "start", a console window pops up and it is in the programDir folder. If I then manually type "idp input.txt" I get the expected behavior.
Second approach:
I also used ProcessBuilder after some googling on the subject. I tried this piece of simple code:
String[] command = {"CMD", "/C", "idp input.txt"};
ProcessBuilder pb = new ProcessBuilder(command);
pb.directory(new File(programDir));
Process proc = pb.start();
Now nothing happens and the program does not terminate.
Again, if I add "start" as one of the parameters in "command", a console window pops up in the right location and if I then manually type "idp input.txt", it works. So I have no idea why the code doesn't work.
One interesting thing: the idp.bat file calls a kbs.exe process. When I run the second piece of code, no kbs.exe appears in my task manager. However, as soon as I terminate the program, it briefly makes an appearance. Does that mean my code gets stuck in a loop somewhere or something?
Any help appreciated!

Run some arguments in command line from java (using Eclipse)

Very basic command-line related question:
I have never tried to run anything in command line from java before and am struggling with the basics - other online information doesn't seem to work for my example, or I'm not understanding it.
In command line this is what it looks like:
C:\gnuplot\binary>gnuplot 15FebPlotFile.gp
All I have to do in command line is navigate to the correct file location (C:\gnuplot\binary) and then type gnuplot 15FebPlotFile.gp and it runs the thing I need (which simply generates a PDF and saves it to that file location)
I've seen people use Runtime and Process like on this site http://www.java-tips.org/java-se-tips/java.util/from-runtime.exec-to-processbuilder.html but I don't understand how I call the various command, like cd C:\gnuplot\binary and then from that location get it to run gnuplot 15FebPlotFile.gp.
If anyone could give me any advice on an approriate site to look at or some lines of code that might help me I'd be really greatful.
Thank you
You can work with ProcessBuilder, and then you can set the working directory of the process using ProcessBuilder#directory(File dir):
ProcessBuilder processBuilder = new ProcessBuilder("gnuplot", "15FebPlotFile.gp");
processBuilder.directory(new File("C:\\gnuplot\\binary"));
Process p = processBuilder.start();
I hope here you can find some code examples and solutions
Run command prompt from java?
changing the working-directory of command from java

Problem with run DOS command in Java

Dear all
I want to execute a EXE file in Java, but I was not able to do it correctly.
Originally, in DOS command prompt, my command is like this:
C:>\crf_test.exe model <inputfile.txt> outputfile.txt
Note: the input file name must be place in the brackets <>. It always gave me good results when run it in DOS window.
When I want my java program to call above command, I do like this:
Process p = Runtime.getRuntime().exec("crf_test.exe model <inputfile.txt> outputfile.txt");
However, the output of this command is "no such file or directory: "
I guest Java doesn't like the brackets <> in DOS command. I also remove <> out, but exe file did not accept that.
So now how can I deal with this problem? Please give me a sollution
Thank you much much
There are potentially two problems. Firstly, the one that others have mentioned - crf_test.exe may not be in your path. It's hard to tell whether your output of "no such file or directory" is from crf_test.exe or from Java trying to find crf_test.exe.
Secondly though, running it from DOS you're not really putting the filename in brackets - you're redirecting system input from the input file to the output file, so the logical grouping is:
crf_test.exe model < inputfile.txt > outputfile.txt
Now when you're running it from Java, it's genuinely trying to pass <inputfile.txt> as a second command-line argument, and outputfile.txt as a third. My guess is that crf_test.exe is then trying to load those as files, and giving "no such file or directory" as an error.
You'll need to load the data from inputfile.txt yourself and pass it in via Process.getOutputStream, and then read the output from Process.getInputStream and write it to outputfile.txt.
Alternatively, you could run cmd.exe and pass in the whole command as an argument - that way the shell will perform the redirection for you as if you were running from a DOS prompt.
The angle brackets are redirection operators: <inputfile.txt causes the input to be read in from inputfile.txt instead of the keyboard, >outputfile.txt causes the output to be written to outputfile.txt instead of the screen. This facility is provided by the shell, however when invoking your program with the Java runtime the shell is not present. Invoke via the shell, like this:
Runtime.getRuntime().exec("cmd /c crf_test.exe model <inputfile.txt> outputfile.txt");
...or redirect input and output using facilities provided by Java; see e.g. this question.
try this
Process p = Runtime.getRuntime().exec("crf_test.exe","/c","model outputfile.txt");
The problem is that the crf_test.ext is missing in your current execution folder. You need either copy the executable or use the absolute path or set the PATH variable to include the necessary path.
If I understand the problem right, you want to call
crf_test.exe model
with input from file inputfile.txt and output to outputfile.txt
You have to redrect in and out and call only crf_test.exe model. How do redirect in and out is described in how to redirect stdin to java Runtime.exec ?

Java ProcessBuilder showing console of started java application?

I have a JAVA application that launches (using ProcessBuilder) another JAVA application like this:
String val = "something";
ProcessBuilder processBuilder = new ProcessBuilder("java", "-classpath", dir, appName, val);
Process p = processBuilder.start();
Now, this works fine, appName is launched with the parameter val and it runs and works ... great ... the problem is no Console Window appears ... appName does a LOT of outputting to the console and we need to see it ... how can I start the process with a console?
I am trying stuff like ("CMD.exe", "java", "-classpath", dir, appName, val), etc... but I can't get it right ...
Also, I can't redirect the streams, my program can actually start 5-10 of these appName's, each should have their own console window showing their own information.
Any help would be much appreciated.
Thanks,
console windows are generally not the most reliable form of logging. they only store a set amount of information (buffer) and can behave differently across platforms.
i strongly suggest logging to a file using something like log4j and if you need to see it real time use a tail like program (i see you're using windows).
in addition to this, seeing as you want the windows visible at all times and launching a tail program for each log might be annoying, i'd write my own log window in java swing.
the basic idea is to not rely on the OS too much.
Tried Runtime.getRuntime().exec("cscript java -classpath ..."); ?
Anyway, consider using a logging framwork (log4j, commons-logging), because opening 5 consoles is not the most clever thing to do.
I call a few shell scripts via Process to open a command line window and launch whatever I need. As long as the scripts don't detach - you can usually stop any shell command from doing this -java will still hold the running process.
I did it in linux but the concept should be similar.
#!/bin/bash
# To open a process in a new window.
gnome-terminal -x ./your-real-shell-script-here.sh "$#"
the real script will have your java execution in it, such as:
#!/bin/bash
java -jar your-jar-file.jar "$#"
I think you can use javaw to run on windows, so you might only need the one shell script.
A Console object only exists when you execute java.... from a console. Otherwise, the call to obtain one returns null.
If you want to see a console, you need to open a command shell console (e.g. windows cmd.exe or Unix bash shell window) and type:
java -classpath="..." com.example.appName arg1
If you want to run in a different manner, sorry to say, logging to Console is not for you. Instead, log using one of:
log4j
slf4j
logback

Categories

Resources