Hide BAT file window when invoking it from Java - java

I'm invoking the execution of a BAT file from Java with the Runtime object.
Is it possible to hide the BAT window during the execution of the script? How is it possible?

Try using javaw rather than java to run the script.
http://docs.oracle.com/javase/1.4.2/docs/tooldocs/windows/java.html
Update: Sorry, I think I read the question wrong. I know I've suppressed a .bat window doing something along these lines before:
http://www.geekstogo.com/forum/topic/56092-hide-the-command-prompt-windows/

Invoke start as the first command in your process builder, with the /b option:
ProcessBuilder builder = new ProcessBuilder("start", "/b", "<mybatchcommand>");
// .. set environment, handle streams
builder.start();
The /b options suppresses the command window.

Process p = Runtime.getRuntime().exec("scriptName.vbs");
In scriptName.vbs you write
var WindowStyle_Hidden = 0
var objShell = WScript.CreateObject("WScript.Shell")
var result = objShell.Run("cmd.exe /c abc.bat", WindowStyle_Hidden)

Related

Java Run System Command and Ignore Output

Is there any sane way to run a system command from Java that ignores STDOUT and STDERR? For example, when I try the following:
Process p = Runtime.getRuntime().exec("some_executable_path param1 param2 >NUL 2>&1");
Java tries to parse the command, and ends up escaping the arguments (e.g., prevents the output from being redirected). If I don't redirect STDOUT/STDERR, the buffers fill up and prevent the system call from exiting. The following does what I want, but is extremely cumbersome and creates expensive resources just to throw the output of the system call away:
ProcessBuilder pb = new ProcessBuilder("some_executable_path", "param1", "param2");
pb.redirectErrorStream(true);
final Process p = pb.start();
final Thread redirectToNull = new Thread(() -> {
final InputStream stdout = process.getInputStream();
try {
while (stdout.read() != -1);
} catch (final Exception e) {
// Don't care
}
}, "Output Consumer Thread");
redirectToNull.setDaemon(true);
redirectToNull.start();
I realize the Java design team is known to be masochistic, but this is ridiculous. I would prefer to deliver a batch or Perl script that wraps the system call with my application rather than use the above code. There has to be an easier way to accomplish this.
So the question is, is there any sane way to run a system command from within Java and ignore the output printed to STDOUT/STDERR?
It's not that Java 'prevents' redirection, it just doesn't affirmatively do it, and neither does your program. When you give CMD a command like program arg1 arg2 >out 2>err <in, it is CMD that sets up those redirections and then invokes program with arg1 arg2 only, not >out etc. On Unix the shells do the same -- there is a choice of several shells, but all of them handle redirection like this. Similarly pipes are set up by CMD or shells, not by either or all of the programs run in those pipes.
Thus on Windows the way to do this is either run CMD and have it do the redirections:
Process p = new ProcessBuilder ("cmd", "/c", "program arg1 arg2 >NUL 2>&1").start();
// this uses CMD's default parsing for args, so they must not contain space
// unless you insert 'data' quotes, or things that look like a substitutable %var%
or (assuming Java7+) tell ProcessBuilder to do the redirections:
pb.redirectOutput (new File("NUL")).redirectErrorStream(true)

Calling perl from java

How do I call a perl script from java? Currently I have this code but a create process error =2 keeps coming up.
Process p = Runtime.getRuntime().exec("perl C:/Users/Mahish/Documents/PLUa/src//test.pl");
You need to set full path to your dir perl\bin
Example command to do this in CMD:
SET PATH=%PATH%;c:\perl\bin
and after that you can use:
Process p = Runtime.getRuntime().exec("perl C:/Users/Mahish/Documents/PLUa/src/test.pl");

Get exit value of CMD child process called from java program

In my java program I am trying to run a different program through CMD with its output appearing in a command window in the foreground and then analyze the exit code of the child program (foo) in the main java program. Unfortunately, all I seem to be able to access is the exit code of the CMD window, which is always 0.
The following is a snippet of what I'm doing:
ProcessBuilder pb = new ProcessBuilder();
pb.directory(new File(dir));
pb.command("cmd","/c","start","/wait","foo.exe",arg);
process = pb.start();
exitVal = process.waitFor();
but exitVal is always 0 regardless of how foo exits. How can I get just the exit code of foo?
I'm also pretty new to java so if there's a more elegant way of doing this, I'm open to suggestions.
I found a solution by modifying one of the things I had tried before to account for windows batch being finicky. The solution was to send another command to cmd to tell it to exit with the most recent error code. Earlier I had tried this by appending & exit %errorlevel% to the command but cmd variables are only updated at the end of each command line, not at the end of each command.
To force update, I used %^errorlevel% instead.

Using Runtime Java to execute command in linux not working Return Code not 0

I have a command like
cp -R Folder1/* Folder2/
or
rm -r /images/*.gif
It is not working to I try to run a sample program through Java
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);
return proc.waitFor();
What am i doing wrong?
When you run a process, Java creates three outputs, the exit code, the STDOUT, and the STDERR. A good program running an external process, will check all three.
You are just waiting for the process to terminate, and return the exit code.
An easy way to see what's happening is to 'inherit' the STDOUT/STDERR streams using a ProcessBuilder:
ProcessBuilder pbuilder = new ProcessBuilder("cp", "-R", "Folder1/*", "Folder2/");
pbuilder.inheritIO();
Process proc = pbuilder.start();
return proc.waitFor();
you will get a better idea of what went wrong.
Note also that I used separate String arguments for the command. This helps with ensuring the arguments are passed right to the underlying process.
Try like this:
List<String> cmd = new ArrayList<String>();
cmd.add("bash");
cmd.add("-c");
cmd.add(" rm -rf *.txt");
add the above list in ProcessBuilder then execute.

Passing a string to the Windows command line

Please see the code below
Runtime rt = Runtime.getRuntime();
rt.exec("cmd /c start");
String[] cmd = {"LogParser", "Select top 10 * into c:\temp\test9.csv from application" };
rt.exec(cmd);
It opens the command window but the strings are not passed in after opening. Can someone tell me why this code won't place the strings into the command window?
The option /C means: Carries out the command specified by the string and then terminates.
So the other command is handled as a separated one.
Use OutputStreamWriter and write to the input stream of the process created.
Process p = Runtime.getRuntime().exec("cmd /K start") ;
Writer w = new java.io.OutputStreamWriter(p.getOutputStream());
w.append(yourCommandHere);
Also, the reason for using /K :
/K Run Command and then return to the CMD prompt.
Reference : http://ss64.com/nt/cmd.html
Why not use this:
String[] cmd = { "cmd /c", "LogParser",
"Select top 10 * into c:\temp\test9.csv from application" };
rt.exec(cmd);
Find more info about the exec method here.
You'll first need to start a process as you do in your first two lines of code, but don't use start because that spawns a separate process and returns immediately. Use just LogParser instead, or whatever will make your LogParser process start without involving cmd. After that you need to retrieve the OutputStream of the Process object created by exec and write your select command into it. You will also need to read from the Processs InputStream to see the response. None of this will be visible in a separate command-prompt window; you'll need to process everything through Java and it will involve some multithreading as well.
As I said in my comment - 'They are executed as separate commands, they are not related just because you executed one before the other'
From the Runtime.exec( string ) javadoc -
Executes the specified command and arguments in a separate process.
You need to chain the commands together to get cmd to process your command, I believe you need to use the \k flag to specify what commands you need executed on the command line.
Runtime rt = Runtime.getRuntime();
String start = "cmd /k ";
String cmd = "LogParser;\n" Select top 10 * into c:\temp\test9.csv from application";
rt.exec(start + cmd);
Not tested as I don't have windows, but it should be similar to this.

Categories