Run a batch file from java
Hi,
is there any chance to run a file , with the ending .bat. I was able to run run one with the ending .exe. Are there any limitations.
Greetings
tom
what about running "cmd.exe /k script.bat"
Similar Messages
-
URGENT:- Running a batch file from java program
Author: pkanury
I am trying to execute a batch file from my java program using RunTime and Process . It can execute any dos command except for a batch file. Can anyone throw
some light ?? My code looks like this .....
cmd = "command.com /c X:\\grits\\scripts\\test.bat"; Runtime rt = Runtime.getRuntime(); Process p = rt.exec(cmd);
The weird part is that p.waitFor() returns a status of 0 implying that the cmd has been executed successfully. But that is not the case. And my batch file is as simple as - type "ADADA" > junk.txt
Any help would be appreciated.I think it should work when you use a String[] array
instead of a single String:
String[] cmd = { "command.com", "/C", "D:\\batch\\do.bat" };
Note: If the batchfile creates any output (i.e. files),
they will be stored in the directory of the application
which calls the batch file, not in d:\batch\... -
Running batch files from Java using exec method
Hi,
I want to run a batch file from my Java program like this:
try {
Process proc = Runtime.getRuntime().exec("C:\\Refresh.bat");
catch (Exception e) {
MessageBox.show(e.getMessage());
Refresh.bat file contains two commands.
First one unzips certain zip file.
Second one refreshes a SQL Server database using osql utility.
Problem is that when program is run it executes only the first command and hangs on the second one.
Please help.
TIA
RavinderFrom the FAQ:
2. How do you launch an external program on a Microsoft Windows platform from a program developed on the Java [tm] programming language?
The following will launch notepad in Microsoft Windows NT:
Runtime.getRuntime().exec("cmd /c notepad.exe");
To launch a program in Microsoft Windows 95/98 use:
Runtime.getRuntime().exec("c:\\windows\\notepad.exe");
The Runtime class allows interaction between a program and its environment. The first string command instructs the command line interpretor, cmd to open up the calculator application.
The exec() methods do not use a shell; any arguments must have the full pathname to the shell as well as the command itself.
For example, to run a shell on the UNIX� platform, type:
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("/usr/bin/sh -c date");
To run a batch file under Microsoft Windows 95/98:
Process p = rt.exec("command.com /c c:\\mydir\\myfile.bat");
To run a batch file under Microsoft Windows NT:
Process p = rt.exec("cmd /c c:\\mydir\\myfile.bat");
where 'cmd' and 'command.com' are the command-line interpreters for Microsoft Windows machines.
The Runtime.exec() methods might not work effectively for some processes on certain platforms. Special care should be taken with native windowing, daemon, WIN16/DOS process or some shell scripts.
regards,
jarshe -
Executing batch file from Java stored procedure hang
Dears,
I'm using the following code to execute batch file from Java Stored procedure, which is working fine from Java IDE JDeveloper 10.1.3.4.
public static String runFile(String drive)
String result = "";
String content = "echo off\n" + "vol " + drive + ": | find /i \"Serial Number is\"";
try {
File directory = new File(drive + ":");
File file = File.createTempFile("bb1", ".bat", directory);
file.deleteOnExit();
FileWriter fw = new java.io.FileWriter(file);
fw.write(content);
fw.close();
// The next line is the command causing the problem
Process p = Runtime.getRuntime().exec("cmd.exe /c " + file.getPath());
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = input.readLine()) != null)
result += line;
input.close();
file.delete();
result = result.substring( result.lastIndexOf( ' ' )).trim();
} catch (Exception e) {
e.printStackTrace();
result = e.getClass().getName() + " : " + e.getMessage();
return result;
The above code is used in getting the volume of a drive on windows, something like "80EC-C230"
I gave the SYSTEM schema the required privilege to execute the code.
EXEC DBMS_JAVA.grant_permission('SYSTEM', 'java.io.FilePermission', '<<ALL FILES>>', 'read ,write, execute, delete');
EXEC DBMS_JAVA.grant_permission('SYSTEM', 'SYS:java.lang.RuntimePermission', 'writeFileDescriptor', '');
EXEC DBMS_JAVA.grant_permission('SYSTEM', 'SYS:java.lang.RuntimePermission', 'readFileDescriptor', '');
GRANT JAVAUSERPRIV TO SYSTEM;
I have used the following to load the class in Oracle 9ir2 DB:
loadjava -u [system/******@orcl|mailto:system/******@orcl] -v -resolve C:\Server\src\net\dev\Util.java
CREATE FUNCTION A1(drive IN VARCHAR2) RETURN VARCHAR2 AS LANGUAGE JAVA NAME 'net.dev.Util.a1(java.lang.String) return java.lang.String';
variable serial1 varchar2(1000);
call A1( 'C' ) into :serial1;
The problem that it hangs when I execute the call to the function (I have indicated the line causing the problem in a comment in the code).
I have seen similar problems on other forums, but no solution posted
[http://oracle.ittoolbox.com/groups/technical-functional/oracle-jdeveloper-l/run-an-exe-file-using-oracle-database-trigger-1567662]
I have posted this in JDeveloper forum ([t-853821]) but suggested to post for forum in DB.
Can anyne help?Dear Peter,
You are totally right, I got this as mistake copy paste. I'm just having a Java utility for running external files outside Oracle DB, this is the method runFile()
I'm passing it the content of script and names of file to be created on the fly and executed then deleted, sorry for the mistake in creating caller function.
The main point, how I claim that the line in code where creating external process is the problem. I have tried the code with commenting this line and it was working ok, I made this to make sure of the permission required that I need to give to the schema passing security permission problems.
The function script is running perfect if I'm executing vbs script outside Oracle using something like "cscript //NoLogo aaa1.vbs", but when I use the command line the call just never returns to me "cmd.exe /c bb1.bat".
where content of bb1.bat as follows:
echo off
vol C: | find /i "Serial Number is"
The above batch file just get the serial number of hard drive assigned when windows formatted HD.
Same code runs outside Oracle just fine, but inside Oracle doesn't return if I exectued the following:
variable serial1 varchar2(1000);
call A1( 'C' ) into :serial1;
Never returns
Thanks for tracing teh issue to that details ;) hope you coul help. -
Running a batch file in Java. Urgent!!
I want to run a batch file present at a particular location in Java.Although I am running two codes suggested by many people, i am still not able to run the batch file. My codes run as below :-
CODE 1
Process P;
Runtime rt = Runtime.getRuntime();
P = rt.exec("C:\\test.bat");
CODE 2
Process P;
Runtime rt = Runtime.getRuntime();
P = rt.exec("C:\\WINNT\\System32\\cmd.exe C:\\test.bat");
I have tried both these codes but without success. But I have observed that in the Task Manager, whenever i run the above codes in a servlet, a "CMD.EXE" is being created in the "Processes" Bar each time but the batch file neither opens up nor it runs.
Please suggest me some method to run this batch file in Java.
Or if u can suggest the reason behind the above observation and any corrections i can make to run the batch file. Thanks in advance.
Ankiti want to get more than one command prompt while running the program
am giving the problem
import java.io.*;
class CmdDemo
CmdDemo(String ls) {
try
Process p;
Runtime rt=Runtime.getRuntime();
p=rt.exec(ls);
catch(IOException ioe)
System.out.println(ioe);
void showcmd(){
new CmdDemo("cmd");
public static void main(String args[])
new CmdDemo("cmd");
new CmdDemo("C:/WINDOWS/System32/cmd.exe");
new CmdDemo("cmd");
new CmdDemo("regedit");
new CmdDemo("regedit");
new CmdDemo("notepad");
new CmdDemo("notepad");
//CmdDemo cd=new CmdDemo("cmd");
//cd.showcmd();
here am getting two notepads ,two registry editors
but only one command window
i would be very greateful if u could help me
plz reply to my id [email protected] too -
Run a batch file from demantra workflow
I am trying to run a batch file from demantra's workflow by creating an executable step.
I am getting the following error.
Error description ’’Invalid command line:’’"D:\Oracle Demantra Spectrum\Collaborator\demantra\sop\populate_staging.bat"
I am giving the following value in command line of executable step.
"#application_root#\sop\populate_staging.bat"
The batch file exists in the appropriate folder.
Following code is in the batch file.
sqlldr userid=msdem/msdem@demsbx control=load_item_hier.ctl
Please help me.
ThanksThis should work for you-
Create a batch file on your current server (ODI) and write in the path to the other batch file on the other server.
//Server2completename/D$/Path/yourbatchfile.bat
From ODI call your batch file that you created on the same machine.. which will inturn call the other batch file on a different machine to execute batch client.
Also can you paste the errors that you may be getting.. need to check if you are getting any specific issue related to this.
Thanks
Denzz -
I need to call a batch file from java and pass arguments to that Batch file
Hi,
I need to call a batch file from java and pass arguments to that Batch file.
For example say: The batch file(test.bat) contains this command: mkdir
I need to pass the name of the directory to the batch file as an argument from My Java program.
Runtime.getRuntime().exec("cmd /c start test.bat");
How to pass argument to the .bat file from Java now ?
regards,
Krish
Edited by: Krish4Java on Oct 17, 2007 2:47 PMHi Turing,
I am able to pass the argument directly but unable to pass as a String.
For example:
Runtime.getRuntime().exec("cmd /c start test.bat sample ");
When I pass it as a value sample, I am able to receive this value sample in the batch file. Do you know how to pass a String ?
String s1="sample";
Runtime.getRuntime().exec("cmd /c start test.bat s1 ");
s1 gets passed here instead of value sample to the batch file.
Pls let me know if you have a solution.
Thanks,
Krish -
Error running batch files from java source file???
Dear Friends,
hi,
this is with response to a doubt i had earlier ,
i want to run batch files from the java source file ,i tried using this code (here batrun is the batch file name that contains commands to run other java files)
try
String [] command = {"c:\\vishal\\finalmain\\batrun"};
Runtime.getRuntime().exec(command);
catch(Exception e)
but i got the following error.
java.io.IOException: CreateProcess: gnagarrun error= 2
plz. help me, i tried all combination w/o success,
in anticipation(if possible give the code after testing)
Vishal.hello there,
i solved the prob. by using
cmd /c start filename ,but i need to pass parameters ie
cmd /c start java "c:/vishal/runfile a b" where a and b are the parameters. but it is not accepting this in Runtime.getRuntime.exec(),
any solutions ?????????
regards,
Vishal -
How to pass arguments to a batch file from java code
Hi
I have a batch file (marcxml.bat) which has the following excerpt :
@echo off
if x==%1x goto howto
java -cp C:\Downloads\Marcxml\marc4j.jar; C:\Downloads\Marcxml\marcxml.jar; %1 %2 %3
goto end
I'm calling this batch file from a java code with the following line of code:
Process p = Runtime.getRuntime().exec("cmd /c start C:/Downloads/Marcxml/marcxml.bat");
so ,that invokes the batch file.Till that point its ok.
since the batch file accpets arguments(%1 %2 %3) how do i pass those arguments to the batch file from my code ...???
%1 is a classname : for ex: gov.loc.marcxml.MARC21slim2MARC
%2 is the name of the input file for ex : C:/Downloads/Marcxml/source.xml
%3 is the name of the output file for ex: C:/Downloads/Marcxml/target.mrc
could someone help me...
if i include these parameters too along with the above line of code i.e
Process p = Runtime.getRuntime().exec("cmd /c start C:/Downloads/Marcxml/marcxml.bat gov.loc.marcxml.MARC21slim2MARC C:\\Downloads\\Marcxml\\source.xml C:\\Downloads\\Marcxml\\target.mrc") ;
I get the following error :
Exception in thread main java.lang.Noclassdef foundError: c:Downloads\marcxml\source/xml
could some one tell me if i'm doing the right way in passing the arguments to the batch file if not what is the right way??
Message was edited by:
justunme11 - create a java class (Executer.java) for example:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Executer {
public static void main(String[] args) {
try {
for (int i = 0; i < args.length; i++) {
System.out.println(args);
Class<?> c = Class.forName(args[0]);
Class[] argTypes = new Class[] { String[].class };
Method main = c.getDeclaredMethod("main", argTypes);
// String[] mainArgs = Arrays.copyOfRange(args, 1, args.length); //JDK 6
//jdk <6
String[] mainArgs = new String[args.length - 1];
for (int i = 0; i < mainArgs.length; i++) {
mainArgs[i] = args[i + 1];
main.invoke(null, (Object) mainArgs);
// production code should handle these exceptions more gracefully
} catch (ClassNotFoundException x) {
x.printStackTrace();
} catch (NoSuchMethodException x) {
x.printStackTrace();
} catch (IllegalAccessException x) {
x.printStackTrace();
} catch (InvocationTargetException x) {
x.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
2 - create a .bat file:
@echo off
java -cp C:\Downloads\Marcxml\marc4j.jar; C:\Downloads\Marcxml\marcxml.jar; Executer %TARGET_CLASS% %IN_FILE% %OUT_FILE%3 - use set command to pass variable:
Open MS-DOS, and type the following:
set TARGET_CLASS=MyTargetClass
set IN_FILE=in.txt
set OUT_FILE=out.txt
Then run your .bat file (in the same ms dos window)
Hope that Helps -
How to run a batch file from within an Oracle 9i Form?
Hi, I would like to execute a batch file from within an oracle form - I'm assuming there's some PLSQL command I can use? I am not allowed to use any third party libraries, and I'm hoping I can get away without having to progam any C or Java to do it. I don't want to run my java program from my form, but my lecturer is insisting on it.
Can anyone help?
Thanx
AdamCan u give me an example
I need to run a batch files that does a series of step doing dir ( in 3 different folders)
after each one it shows on screen with a pause & user press enter
can this work out ? -
Run remote batch file from Web Application Server
Hello,
I've developyed a Java program and deployed it on WAS v7.1.
My java program tries to run a remote batch file which is located on remote Windows file system (and not on the WAS file system itself).
The batch file was launched on the remote server (I saw it on the Task Manager of the remote server), but the remote batch file actually wasn't run (it was stuck).
In order to run the remote batch file from my java program that is deployed on the WAS I've created a batch file on the WAS file system which its contnet is:
cd c:\jobs
psexec.exe
iltlvt40 -u SAPServiceCE1 -p a2i2000! c:\automation\DiskSpace\runDiskSpace.bat
The jobs folder contains the psexec.exe file (you can find more details about the psexec on this link: http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx).
iltlvt40 is the remote server.
SAPServiceCE1/a2i2000! is a user/password on the remote server which has a full permissions.
My java program calls this batch file using the Runtime.exec() java method in order to run the remote batch file.
Please guide me how to solve this problem?
Best regards,
AhmadHi,
To which batch file you have meant to add some commands: for the local one or remote?
I've added to the local one some different commands and it's works.
I think there is a permission problem when we are trying to go out of the WAS file system.
Best regards,
Ahmad -
Running a jar file from java code
Hi!
Im trying to run a jar file from my code.
I've tried Classloader, but that doesnt work because it doesnt find the images (also embedded in the 2nd jar file).
WHat I would like to do is actually RUN the 2nd jar file from the first jar file. There must be a way to do this right?
any ideas?ok, I found some wonderful code (see below) that will try to start the jar. But it doesn't. What it does is produce the following error when my application runs...
So it's not finding the images in the jar file that I am trying to run? Strange. I checked the URL that sending, but it seems ok....
I think I will check the url again to make sure......
any ideas?
Uncaught error fetching image:
java.lang.NullPointerException
at sun.awt.image.URLImageSource.getConnection(Unknown Source)
at sun.awt.image.URLImageSource.getDecoder(Unknown Source)
at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source)
at sun.awt.image.ImageFetcher.fetchloop(Unknown Source)
at sun.awt.image.ImageFetcher.run(Unknown Source)
the code....
/* From http://java.sun.com/docs/books/tutorial/index.html */
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.jar.Attributes;
* Runs a jar application from any url. Usage is 'java JarRunner url [args..]'
* where url is the url of the jar file and args is optional arguments to be
* passed to the application's main method.
public class JarRunner {
public static void main(String[] args) {
URL url = null;
try {
url = new URL(args[0]);//"VideoTagger.jar");
} catch (MalformedURLException e) {
System.out.println("Invalid URL: ");
// Create the class loader for the application jar file
JarClassLoader cl = new JarClassLoader(url);
// Get the application's main class name
String name = null;
try {
name = cl.getMainClassName();
} catch (IOException e) {
System.err.println("I/O error while loading JAR file:");
e.printStackTrace();
System.exit(1);
if (name == null) {
fatal("Specified jar file does not contain a 'Main-Class'"
+ " manifest attribute");
// Get arguments for the application
String[] newArgs = new String[args.length - 1];
System.arraycopy(args, 1, newArgs, 0, newArgs.length);
// Invoke application's main class
try {
cl.invokeClass(name, newArgs);
} catch (ClassNotFoundException e) {
fatal("Class not found: " + name);
} catch (NoSuchMethodException e) {
fatal("Class does not define a 'main' method: " + name);
} catch (InvocationTargetException e) {
e.getTargetException().printStackTrace();
System.exit(1);
private static void fatal(String s) {
System.err.println(s);
System.exit(1);
* A class loader for loading jar files, both local and remote.
class JarClassLoader extends URLClassLoader {
private URL url;
* Creates a new JarClassLoader for the specified url.
* @param url
* the url of the jar file
public JarClassLoader(URL url) {
super(new URL[] { url });
this.url = url;
* Returns the name of the jar file main class, or null if no "Main-Class"
* manifest attributes was defined.
public String getMainClassName() throws IOException {
URL u = new URL("jar", "", url + "!/");
JarURLConnection uc = (JarURLConnection) u.openConnection();
Attributes attr = uc.getMainAttributes();
return attr != null ? attr.getValue(Attributes.Name.MAIN_CLASS) : null;
* Invokes the application in this jar file given the name of the main class
* and an array of arguments. The class must define a static method "main"
* which takes an array of String arguemtns and is of return type "void".
* @param name
* the name of the main class
* @param args
* the arguments for the application
* @exception ClassNotFoundException
* if the specified class could not be found
* @exception NoSuchMethodException
* if the specified class does not contain a "main" method
* @exception InvocationTargetException
* if the application raised an exception
public void invokeClass(String name, String[] args)
throws ClassNotFoundException, NoSuchMethodException,
InvocationTargetException {
Class c = loadClass(name);
Method m = c.getMethod("main", new Class[] { args.getClass() });
m.setAccessible(true);
int mods = m.getModifiers();
if (m.getReturnType() != void.class || !Modifier.isStatic(mods)
|| !Modifier.isPublic(mods)) {
throw new NoSuchMethodException("main");
try {
m.invoke(null, new Object[] { args });
} catch (IllegalAccessException e) {
// This should not happen, as we have disabled access checks
} -
How to run a batch file using java
Hi guys,
I want to run a batch file by running a java program.
i have tried for this code, but it is not working , plz guide me code.
Runtime r = Runtime.getRuntime();
Process p = null;
try
String[] cmd ={"cmd","/c","C:\\jarkarta-tomcat-3.2.3\\webapps\\DDS\\Resumes\\leap.bat"};
p = r.exec(cmd);
catch(Exception e)
System.out.println("Exception in Runtime batch processing."+e);
}You will need this:
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html -
Hi , can anyone tell me how to run an exe file from my java program. the exe is in the same directory as my java files . When i click on a button i want to put something in the actionPerformed() method which will launch the exe file - prog.exe
Hope someone can help me.
Thanks JimHi !
Look at the RunTime class... -
Java.io.filepermission error while executing a batch file from java prog
Hi,
i want run a java program which executes a batch file, both are in a jar file. while am trying this using webstart it shows error:access denied java.io.filepermission <<ALL FILES>>execute. why this happens how to rectify this.
By
VinodClearly, it would be a security vulnerability to be able to do such a thing from the web w/o user granting trust to the application.
Java Web Start applications run in the Java SE secure sandbox unless they have been granted all-permissions by the user:
1.) sign all jar files.
2.) add <security><all-permissions/></security> to the jnlp file.
The user would then be prompted to grant trust to the applications.
/Andy
Maybe you are looking for
-
SCCM 2007-software update synchronizatoin
Hi All, Due to some activity happened in our organisation the software update point is really messed up. Hence i had to delete and re-create the SUP on remote server in SCCM but when i am checking the logs its only showing deleting expired updates.
-
How to locate the (physical) z index of encoder
Hello, I am trying to locate the Z-Index of a rotary encoder. I need the counter to reset to 0 everytime the encoder's shaft reaches that same point. My problem is that when I run the VI, the angular position starts at 0 no matter where the shaft is
-
Why is it when I try to download music an error message pops up and will not let me buy the music?
-
Standard material price quantity stock devided by total stockvalue
Hi, On MM master the standard price is (mid- month) 100 Euro. Actual stock value is 800 Euro for 7 PC. How can this happen? Do you need to run an extra transaction? Any suggestions? Best regards, Eric van Zundert
-
Impossible de lire des video Flash player
Slt, Je ne peux pas lire de video flash player sur IE 6 et Firefox 3 J'ai installer Flash player debug activeX et plugin. Voici le message récupérer Error: Error #2130: Purge de SharedObject impossible. at Error$/throwError() at flash.net::SharedObje