Trying to show the execution of bat file in eclipse console [duplicate] - java

In my Java application, I want to run a batch file that calls "scons -Q implicit-deps-changed build\file_load_type export\file_load_type"
It seems that I can't even get my batch file to execute. I'm out of ideas.
This is what I have in Java:
Runtime.
getRuntime().
exec("build.bat", null, new File("."));
Previously, I had a Python Sconscript file that I wanted to run but since that didn't work I decided I would call the script via a batch file but that method has not been successful as of yet.

Batch files are not an executable. They need an application to run them (i.e. cmd).
On UNIX, the script file has shebang (#!) at the start of a file to specify the program that executes it. Double-clicking in Windows is performed by Windows Explorer. CreateProcess does not know anything about that.
Runtime.
getRuntime().
exec("cmd /c start \"\" build.bat");
Note: With the start \"\" command, a separate command window will be opened with a blank title and any output from the batch file will be displayed there. It should also work with just `cmd /c build.bat", in which case the output can be read from the sub-process in Java if desired.

Sometimes the thread execution process time is higher than JVM thread waiting process time, it use to happen when the process you're invoking takes some time to be processed, use the waitFor() command as follows:
try{
Process p = Runtime.getRuntime().exec("file location here, don't forget using / instead of \\ to make it interoperable");
p.waitFor();
}catch( IOException ex ){
//Validate the case the file can't be accesed (not enought permissions)
}catch( InterruptedException ex ){
//Validate the case the process is being stopped by some external situation
}
This way the JVM will stop until the process you're invoking is done before it continue with the thread execution stack.

Runtime runtime = Runtime.getRuntime();
try {
Process p1 = runtime.exec("cmd /c start D:\\temp\\a.bat");
InputStream is = p1.getInputStream();
int i = 0;
while( (i = is.read() ) != -1) {
System.out.print((char)i);
}
} catch(IOException ioException) {
System.out.println(ioException.getMessage() );
}

ProcessBuilder is the Java 5/6 way to run external processes.

To run batch files using java if that's you're talking about...
String path="cmd /c start d:\\sample\\sample.bat";
Runtime rn=Runtime.getRuntime();
Process pr=rn.exec(path);`
This should do it.

The executable used to run batch scripts is cmd.exe which uses the /c flag to specify the name of the batch file to run:
Runtime.getRuntime().exec(new String[]{"cmd.exe", "/c", "build.bat"});
Theoretically you should also be able to run Scons in this manner, though I haven't tested this:
Runtime.getRuntime().exec(new String[]{"scons", "-Q", "implicit-deps-changed", "build\file_load_type", "export\file_load_type"});
EDIT: Amara, you say that this isn't working. The error you listed is the error you'd get when running Java from a Cygwin terminal on a Windows box; is this what you're doing? The problem with that is that Windows and Cygwin have different paths, so the Windows version of Java won't find the scons executable on your Cygwin path. I can explain further if this turns out to be your problem.

Process p = Runtime.getRuntime().exec(
new String[]{"cmd", "/C", "orgreg.bat"},
null,
new File("D://TEST//home//libs//"));
tested with jdk1.5 and jdk1.6
This was working fine for me, hope it helps others too.
to get this i have struggled more days. :(

I had the same issue. However sometimes CMD failed to run my files.
That's why i create a temp.bat on my desktop, next this temp.bat is going to run my file, and next the temp file is going to be deleted.
I know this is a bigger code, however worked for me in 100% when even Runtime.getRuntime().exec() failed.
// creating a string for the Userprofile (either C:\Admin or whatever)
String userprofile = System.getenv("USERPROFILE");
BufferedWriter writer = null;
try {
//create a temporary file
File logFile = new File(userprofile+"\\Desktop\\temp.bat");
writer = new BufferedWriter(new FileWriter(logFile));
// Here comes the lines for the batch file!
// First line is #echo off
// Next line is the directory of our file
// Then we open our file in that directory and exit the cmd
// To seperate each line, please use \r\n
writer.write("cd %ProgramFiles(x86)%\\SOME_FOLDER \r\nstart xyz.bat \r\nexit");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close the writer regardless of what happens...
writer.close();
} catch (Exception e) {
}
}
// running our temp.bat file
Runtime rt = Runtime.getRuntime();
try {
Process pr = rt.exec("cmd /c start \"\" \""+userprofile+"\\Desktop\\temp.bat" );
pr.getOutputStream().close();
} catch (IOException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
// deleting our temp file
File databl = new File(userprofile+"\\Desktop\\temp.bat");
databl.delete();

The following is working fine:
String path="cmd /c start d:\\sample\\sample.bat";
Runtime rn=Runtime.getRuntime();
Process pr=rn.exec(path);

This code will execute two commands.bat that exist in the path C:/folders/folder.
Runtime.getRuntime().exec("cd C:/folders/folder & call commands.bat");

import java.io.IOException;
public class TestBatch {
public static void main(String[] args) {
{
try {
String[] command = {"cmd.exe", "/C", "Start", "C:\\temp\\runtest.bat"};
Process p = Runtime.getRuntime().exec(command);
} catch (IOException ex) {
}
}
}
}

To expand on #Isha's anwser you could just do the following to get the returned output (post-facto not in rea-ltime) of the script that was run:
try {
Process process = Runtime.getRuntime().exec("cmd /c start D:\\temp\\a.bat");
System.out.println(process.getText());
} catch(IOException e) {
e.printStackTrace();
}

Related

error with starting cmd in windows using java?

The following method starts the cmd in Windows and it takes a parameter of the command which need to be run.
I have tested this method using the following commands: net users and it worked fine and it printed the users accounts. but if I run the dir command I get the following error:
java.io.IOEXception:
Cannot run program "dir": CreateProcess error=2, The system cannot find the file specified (in java.lang.ProcessBuilder)
Code :
private String commandOutPut;
public void startCommandLine(String s) throws IOException{
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(s); // you might need the full path
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String commandOutPut;
while ((commandOutPut = br.readLine()) != null) {
this.commandOutPut = this.commandOutPut + "\n" + commandOutPut;
}
System.out.println(this.commandOutPut);
}
Well, obviously, your method does not start cmd. How did you get this notion?
The net command is a standalone command so it runs just fine, but the dir command is not standalone, it is an internal command of cmd.exe, so you cannot run it without launching cmd.exe to execute it.
To get it to work you will have to pass not dir but cmd.exe /c dir or something like that.
Don't know if this perception can help you. But, seems that "net users" are recognized as Windows command, since "Execute" dialog can run it.
But, for some reason, the "dir" command aren't. When try to run, Windows responds that command was not found.
Additionaly, I tried run Command with inline arguments too, but the arguments are simply ignored. (sorry for bad english)
My best guess is that this is because "net" is a real executable (there is a file WINDIR\System32\net.exe"), while "dir" is a builtin command of the command interpreter - it has no executable and is directly executed within cmd.exe.
Howevever you may get around this be invoking "dir" command inside the cmd process. The syntax - as per Microsoft docs - is:
cmd /c dir
There are also some related answers on the site:
How to execute cmd commands via Java
Run cmd commands through java
You can use the following code for this
import java.io.*;
public class demo
{
public static void main(String args[])
{
try
{
Process pro=Runtime.getRuntime().exec("cmd /c dir");
pro.waitFor();
BufferedReader redr=new BufferedReader(
new InputStreamReader(pro.getInputStream())
);
String ln;
while((ln = redr.readLine()) != null)
{
System.out.println(ln);
}
}
catch(Exception e) {}
System.out.println("Done");
}
}

Process is not completing even after putting the waitFor function

i am new to this Process Thing in java and i am having a problem with this shell command that i want to run in java.
I have this file with a large set of data in it and i want to convert it using XSL.
The command is working fine if run on cmd.exe but is not working in java code.
I have used the process wait too but still there is no output. Please help.
Thanks
Small fragment of code
String c="java -Xmx1g -jar c:\\temp\\FileConverter.jar xmlTransform title \"Data\" root \"c:\\temp\\\" src \"c:\\temp\\input.xml\" xsl \"converter.xsl\" xsl:MEMBER_CODE \"111\" xsl:MEMBER_NAME \"ABC\" xsl:MEMBER_PASSWORD \"abc\" dst \"c:\\temp\\dummy.xml\" src-error \"c:\\temp\\error\"";
Runtime rt = Runtime.getRuntime();
try {
Process proc = rt.exec(c);
synchronized (proc) {
proc.wait(10000);
}
System.out.println("Done");
}catch (IOException e) {
e.printStackTrace();
}

.jar not executing and showing the System.out.print(); output

My problem is when to call jar file using
Runtime.getRuntime().exec() method, my .jar is not executing and showing its output
Coding is like that
public static void main(String[] args) {
String execJar = "java -jar C:\test.jar";
try {
Process p = Runtime.getRuntime().exec(execJar);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
When I used this "java -jar C:\test.jar" in command prompt, my .jar is not executing thus not showing System.out output.
Does anybody know how I can make this work?
Thanks.
ProcessBuilder pb = new ProcessBuilder("java", "-Xmx1024m", "-Xms1024m",
"-DTOOLS_DIR=C://", "-Daoi=whole",
"-jar", "C://calc.jar");
try {
pb.start();
} catch (IOException ex) {
System.out.print("EEE"+ex);
}
This is easy to follow as it has simple paths so you can try it and let it run easily
When you execute a process from within Java, it will have it's own standard out and standard error streams in that particular process. To access those, you have to get the corresponding streams from the Process object you have created.
p.getOutputStream(); // System.out
p.getErrorStream(); // System.err
Where do you expect the System.out to go ?.
When the process is spawned, the input/output and error streams are opened between the spawning and spawned process. You should consume the input and error (these represent the process output, despite the confusing name), otherwise your spawned process will block, waiting for the streams' contents to be consumed.
See this answer for more info.
ProcessBuilder pb = new ProcessBuilder("java", "-Xmx1024m", "-Xms1024m",
"-DTOOLS_DIR=F://Net Beans Work Space//calc//dist", "-Daoi=whole",
"-jar", "F://Net Beans Work Space//calc//dist//calc.jar");
pb.start();
Use this code it will surely run your jar file what you have to change is the paths in above code please reply it will work for you I will be thankful for you kind reply

Why doesn't the Java console show when using ProcessBuilder?

I use the following to launch a Java application from another Java app.
ProcessBuilder pb = new ProcessBuilder(javaPath + javaCommand, maxMemStr,
minMemStr, stackSizeStr, jarCommand, jarfile, jarArg);
try {
Process p = pb.start();
} catch (IOException ex) {
Logger.getLogger(launch.class.getName()).log(Level.SEVERE, null, ex);
}
where javaCommand is either java or javaw (javaPath is empty most of the time unless a user points to an alternate path). The problem is, after the app launches, even when I verify the process list to contain java, it doesn't show the console.
Is it because PrcoessBuilder doesn't invoke the command shell? Is there a way to show the console programatically?
Thanks in advance.
This is because the "command console" itself is a process that attaches to the std-in/-out/-err streams of another process and displays them on the screen. When you launch Java all by itself, no other processes will be handling those streams, hence the lack of a command console. To get the results you want, you will need to launch a new instance of the command console and subsequently have it run your custom java command.
There may be a better way to do this... but I think the solution to this is going to be platform-dependent. In Windows, you could do something like:
ProcessBuilder pb = new ProcessBuilder("start", "\"JAwesomeSauce\"", "cmd.exe",
"/k", javaPath + javaCommand, maxMemStr, minMemStr, stackSizeStr, jarCommand,
jarfile, jarArg);
try {
Process p = pb.start();
} catch (IOException ex) {
Logger.getLogger(launch.class.getName()).log(Level.SEVERE, null, ex);
}
I assume you could do something similar in Linux/Mac if that's the O/S you're using.
You may want to run the command like this:
cmd /K java ...
or
cmd /C java ...
As far as I remember the Processbuilder opens a pipe to a specific process.
Your command window is a process itself with all you see. If you enter commands the cmd/bash usually creates new processes and attaches to them.

Running .jar in Java

I want to run a .jar file in Java, but I get an exception and it doesn't work. In the directory C:/Users/Administrator/Desktop/apache-solr-4.0.0/example, I have a file called start.jar.
My last example this, but it throws an exception. What do I have to do in order to fix it?
public void runStart() {
try {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("C:\\Users\\Administrator\\Desktop\\apache-solr-4.0.0\\example\\start.jar");
} catch (IOException ex) {
Logger.getLogger(SolrForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
You need to exec with java -jar in the command line, otherwise you're not really executing anything.
e.g. rt.exec("java -jar myjar.jar");
Oh, and you'll need to wait for the process to finish; otherwise it may get terminated unexpectedly when it drops out of scope.
When you try to run that command in a console, that doesn't work as well. A jar file is not an executable by itself, but it can be executed by Java.
Try to do it like this:
public void runStart() {
try {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("java -jar C:\\Users\\Administrator\\Desktop\\apache-solr-4.0.0\\example\\start.jar");
} catch (IOException ex) {
Logger.getLogger(SolrForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
This way you start Java, saying that you give it a jar. If Java is in your path (or in the current directory), it should work.
You are passing only a file, that is note an executable application. Assuming that your Java enviroment is configured, you should change your line to this:
Process p = rt.exec("java - jar C:\\Users\\Administrator\\Desktop\\apache-solr-4.0.0\\example\\start.jar");
Try with something like this:
rt.exec("c:\\java_path\\bin\\java -jar C:\\Users\\Administrator\\Desktop\\apache-solr-4.0.0\\example\\start.jar");
Make sure to replace c:\\java_path\\bin\\java with your actual absolute path to the java binary.

Categories