java runtime cmd date & time commands - java

I managed to change system time and date using runtime in java. However I have to run this two commands one at a time opening two command prompts instead of one because if run both commands at the same time the command prompt gets them as one invalid command
//this is the working code that opens two cmd`s:
Runtime rt = Runtime.getRuntime();
rt.exec("elevate.cmd cmd.exe /c time 11:30");
rt.exec("elevate.cmd cmd.exe /c date 02-04-2012");
//this is the code that I think it should open one cmd and execute both of the commands
Runtime rt = Runtime.getRuntime();
rt.exec("elevate.cmd cmd.exe /C time 11:25 /C date 02-05-2012");
But the cmd is returning "The system cannot accept the time entered".
Note: the elevate.cmd is a batch file I use it to run the cmd as administrator(win7) and you can download it from here.
How can I make the system change both time and date by opening cmd once? Or what other choices do I have?

Try solutions from this SOq:
How to execute cmd commands via Java
Basically, create a process and then "write" commands to it as if you were an user typing them. I don't have Win7 to test (don't know how it will behave in combination with elevated privilege prompts), but it works for me on Ubuntu 11.10 - hope it works for your case, too.
Alternatively, you can make another .cmd file (called e.g. changedt.cmd) that will contain the two commands:
elevate.cmd cmd.exe /c time 11:30
elevate.cmd cmd.exe /c date 02-04-2012
and then run it instead:
Runtime rt = Runtime.getRuntime();
rt.exec("changedt.cmd");
This should work in any case, as you seem to be successfully running pretty much the same thing, but adds another .cmd file.
Hope this helps.

Related

cmd windows path and environment variables unrecognized in Java Command Prompt

I am trying to execute the following
on the command line via the java runtime environment.
Runtime rt = Runtime.getRuntime();
String runtime = "cmd /c start cmd.exe /k \"cd /d C:\\Users\\User\\Documents\\ & python book.py \" "
rt.exec(runtime);
When running the command prompt directly, i.e. python book.py (assuming that I have already changed the location to the correct directory), python runs fine without any issues.
However, when done through java, the command prompt window looks different,
with C:\WINDOWS\system32\cmd.exe instead of displaying Command Prompt.
The above java runtime also gives me 'python' is not recognized as an internal or external command, operable program or batch file. (Whereas the normal command prompt the runs python perfectly fine)
How would I go about including my path and environment variables such that python, or any other path/environment variable, is recognized when I run the command prompt from java?
This may sound naiive but apparently, the solution was to restart the computer. I guess the PATH variables in the command prompt that was run JAVA weren't synchronized like in the other instances of running the command prompt directly.

Command prompt do not close after running batch file which have 'exit' in last line

I am running a batch (ScanProject.bat) file using java by following code
Process p= Runtime.getRuntime().exec("cmd /c start /wait ScanProject.bat "+ BaseProjDir+"\\"+jo.getString("Name")+" "+st.nextToken());
System.out.println("Exit value : "+p.waitFor());
And following is the batch file code :-
%2:
cd %1
ant -f ..\antbuild.xml analyse
exit
Batch file run successfully but problem is command prompt window do not closes automatically and hence Process do not terminated automatically and my program wait for infinite time to complete this process.Please suggest me any technique so that cmd exit after running ant -f ..\antbuild.xml analyse command.
Thanks.
cd /D "Full path of directory" or pushd "Full path of directory" with popd before exit is better to switch the current directory to any directory on any drive (cd and pushd/popd) or even to a network share (just pushd/popd). Run in a command prompt window cd /? and pushd /? for details.
cmd /C starts a new Windows command process with closing the process automatically after last command was executed. Run in a command prompt window cmd /? for details on options of Windows command interpreter.
start is a command to start a new Windows command process or a GUI/hybrid application in a separate process.
So what you do here is starting a new Windows command process which starts a new Windows command process.
Running in a command prompt window start /? outputs the help for this command. start interprets often the first double quoted string as title string for the new command process. This causes often troubles on command lines with at least 1 double quoted string. Therefore usage of start requires often an explicit definition of a title string in double quotes as first argument for start which can be even an empty string, i.e. simply "" as first argument after start.
As it can be read after running exit /? in a command prompt window, this command without /B always exits the current Windows command process immediately. So when ant.exe finished, the command process in which the batch file was processed is definitely terminated.
I'm having no experience on Java development, but in my point of view it should be enough to use the following execution command which does not need a batch file at all.
The Java code line
Process p= Runtime.getRuntime().exec("cmd.exe /C cd /D \"" + jo.getString("Name") + "\" && ant.exe -f ..\\antbuild.xml analyse");
should be enough to
start a new Windows command process,
set the current directory within this command process to the drive and directory specified by jo.getString("Name") which of course must return a directory path with drive letter and using backslashes as directory separators, and on success
execute ant in this directory with the specified parameters
with terminating the Windows command process automatically after console application ant.exe finished if ant.exe is a console application.
I'm not sure if cmd.exe /C is needed at all.
I suggest to test this command first manually from within a command prompt window. Then use it in the Java application if really working and producing the expected result. And finally I would further test if cmd.exe /C is needed at all in Java code.
See Single line with multiple commands using Windows batch file for details about the operator && to run a command after previous command was successful. And see also Why do not all started applications save the wanted information in the text files as expected? for an explanation of console / GUI / hybrid application.
NOTE: There is also Java Runtime method exec(String[] cmdarray, String[] envp, File dir) to execute a command like ant.exe with its parameters -f and ..\antbuild.xml and analyse in the directory defined with third parameter which might be better for this task.
Swap out exit for taskkill, assuming you do not have any other cmd processes running. Not very graceful but it will get the job done.
%2:
cd %1
ant -f ..\antbuild.xml analyse
taskkill /im cmd.exe

Enter commands to Java runtime cmd prompt

Runtime.getRuntime().exec(new String[] {
"cmd",
"/c",
"start",
"cd",
"M:\\MandNDrives\\mwallace\\PROPHET\\PROPHET\\Prophet2012"
"prpht0912" //shortcut to prpht0912.exe
"eorinput" // eorinput.ind, input sheet that prpht0912.exe processes
Opens a command prompt to the dir I need.
To execute the program contained in that folder, I then need to execute "prpht0912 eorinput" from the command prompt like:
M:\MandNDrives\mwallace\PROPHET\PROPHET\Prophet2012>prpht0912 eorinput
However the space in the entry returns an error in the prompt: "The system cannot find the path specified"
It isn't possible to execute two commands via the command line in a single invocation of cmd.exe: cmd.exe /c is followed by a single command, and another /c afterwards would be interpreted as a parameter to that command.
Furthermore, invoking it twice won't get you what you want either, as changes of directory are forgotten when the process exits, so the second invocation would be run in the default working directory of the Java process, not the directory you changed to with your first invocation.
Also, it is unfortunate, but Java doesn't provide a way to change the current working directory of its own process.
As far as I can see it, you have two options:
Make sure your Java program is started with the working directory set to the one you need your child program to run in
Invoke a single .bat file that contains both of the commands you need to run.
To Execute the following command
M:\MandNDrives\mwallace\PROPHET\PROPHET\Prophet2012>prpht0912 eorinput
You need the following
String[] commands = new String[] { "cmd", "/c", "M:\\MandNDrives\\mwallace\\PROPHET\\PROPHET\\Prophet2012\\prpht0912.exe eorinput" };
Runtime.getRuntime().exec(commands);
Note**
When you pass an array, ProcessBuilder would consider only the first element as program and remaining as arguments for that program.
String prog = cmdarray[0];

How to run cmd.exe with command string from Java?

Uff... tried to google but with no result.
Hello everybody. I need to run via cmd.exe the next command from java programm (javascript syntax):
"/c cd c:\prb && Processing.bat c:\prb ext.dat auto"
it means i need to change current directory to c:\prb, write "Processing.bat c:\prb ext.dat auto" and press enter.
My Java code is:
String command = "cmd /c start cmd.exe /K cd c:\\prb Processing.bat c:\\prb prb ext.dat auto";
Process pr = Runtime.getRuntime().exec(command);
pr.waitFor();
but it doesn't work. I suppose that i miss some code between "c:\prb" AND "Processing.bat" in the command line.
Could anybody help me?
I can see at least one mistake: path c:\\prb Processing.bat contains space and therefore must be quoted:
"cmd /c start cmd.exe /K cd \"c:\\prb Processing.bat\" c:\\prb prb ext.dat auto"
I am not sure about c:\\prb prb ext.dat. Is it one path or 2 separate arguments? If it is one argument quote it too.
This time I will write a cope from my memory, I have used like 8 year ago :)
What is you trying to solve it is impossible, no that isn't the proper word, but: you want to launch cmd with a specified working directory, than launch a bat file.
Far as I remember:
Launch the .bat, but give a parameter other working directory
Or:
launch cmd (1 process)
give a param to execute the change directory
give another param to execute the bat file. All from Java, it is more complex.
How to do it it is another question.
here is what should be the command like if you do no specify the working directory:
String command = "cmd /c \"c:\prb\Processing.bat\"";
do not forget to change the working directory if you need. 8 years ago I did, sorry if I am robbing your time, just want to help

How to execute unix commands through Windows/cygwin using Java

I am trying to accomplish two things:
I am running cygwin on Windows7 to execute my unix shell commands and I need to automate the process by writing a Java app. I already know how to use the windows shell through Java using the 'Process class' and Runtime.getRuntime().exec("cmd /c dir"). I need to be able to do the same with unix commands: i.e.: ls -la and so forth. What should I look into?
Is there a way to remember a shell's state?
explanation: when I use: Runtime.getRuntime().exec("cmd /c dir"), I always get a listing of my home directory. If I do Runtime.getRuntime().exec("cmd /c cd <some-folder>") and then do Runtime.getRuntime().exec("cmd /c dir") again, I will still get the listing of my home folder. Is there a way to tell the process to remember its state, like a regular shell would?
It seems that the bash command line proposed by PaĆ­lo does not work:
C:\cygwin\bin>bash -c ls -la
-la: ls: command not found
I am having trouble figuring out the technicalities.
This is my code:
p = Runtime.getRuntime().exec("C:\\cygwin\\bin\\bash.exe -c ls -la");
reader2 = new BufferedReader(new InputStreamReader(p.getInputStream()));
line = reader2.readLine();
line ends up having a null value.
I added this to my .bash_profile:
#BASH
export BASH_HOME=/cygdrive/c/cygwin
export PATH=$BASH_HOME/bin:$PATH
I added the following as well:
System Properties -> advanced -> Environment variables -> user variebales -> variable: BASH, value: c:\cygwin\bin
Still nothing...
However, if I execute this instead, it works!
p = Runtime.getRuntime().exec("c:\\cygwin\\bin\\ls -la ~/\"Eclipse_Workspace/RenameScript/files copy\"");
1. Calling unix commands:
You simply need to call your unix shell (e.g. the bash delivered with cygwin) instead of cmd.
bash -c "ls -la"
should do. Of course, if your command is an external program, you could simply call it directly:
ls -la
When starting this from Java, it is best to use the variant which takes a string array, as then
you don't have Java let it parse to see where the arguments start and stop:
Process p =
Runtime.getRuntime().exec(new String[]{"C:\\cygwin\\bin\\bash.exe",
"-c", "ls -la"},
new String[]{"PATH=/cygdrive/c/cygwin/bin"});
The error message in your example (ls: command not found) seems to show that your bash can't find the ls command. Maybe you need to put it into the PATH variable (see above for a way to do this from Java).
Maybe instead of /cygdrive/c/cygwin/bin, the right directory name would be /usr/bin.
(Everything is a bit complicated here by having to bridge between Unix and Windows
conventions everywhere.)
The simple ls command can be called like this:
Process p = Runtime.getRuntime().exec(new String[]{"C:\\cygwin\\bin\\ls.exe", "-la"});
2. Invoking multiple commands:
There are basically two ways of invoking multiple commands in one shell:
passing them all at once to the shell; or
passing them interactively to the shell.
For the first way, simply give multiple commands as argument to the -c option, separated by ; or \n (a newline), like this:
bash -c "cd /bin/ ; ls -la"
or from Java (adapting the example above):
Process p =
Runtime.getRuntime().exec(new String[]{"C:\\cygwin\\bin\\bash.exe",
"-c", "cd /bin/; ls -la"},
new String[]{"PATH=/cygdrive/c/cygwin/bin"});
Here the shell will parse the command line as, and execute it as a script. If it contains multiple commands, they will all be executed, if the shell does not somehow exit before for some reason (like an exit command). (I'm not sure if the Windows cmd does work in a similar way. Please test and report.)
Instead of passing the bash (or cmd or whatever shell you are using) the commands on the
command line, you can pass them via the Process' input stream.
A shell started in "input mode" (e.g. one which got neither the -c option nor a shell script file argument) will read input from the stream, and interpret the first line as a command (or several ones).
Then it will execute this command. The command itself might read more input from the stream, if it wants.
Then the shell will read the next line, interpret it as a command, and execute.
(In some cases the shell has to read more than one line, for example for long strings or composed commands like if or loops.)
This will go on until either the end of the stream (e.g. stream.close() at your side) or executing an explicit exit command (or some other reasons to exit).
Here would be an example for this:
Process p = Runtime.getRuntime().exec(new String[]{"C:\\cygwin\\bin\\bash.exe", "-s"});
InputStream outStream = p.getInputStream(); // normal output of the shell
InputStream errStream = p.getInputStream(); // error output of the shell
// TODO: start separate threads to read these streams
PrintStream ps = new PrintStream(p.getOutputStream());
ps.println("cd /bin/");
ps.println("ls -la");
ps.println("exit");
ps.close();
You do not need cygwin here. There are several pure Java libraries implementing SSH protocol. Use them. BTW they will solve your second problem. You will open session and execute command withing the same session, so the shell state will be preserved automatically.
One example would be JSch.

Categories