Running command prompt externally from Java

Hi,
Does anyone know how to make a Java program that opens up the command prompt and runs certain commands? Thanks,
Adam

Read this before you use it:
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

Similar Messages

  • How java runs in command prompt and why java runs on it

    how java runs in command prompt and why java runs on it

    command prompt was used before the development of IDEs like RAD,eclipse etc.
    its still used for better understanding of the compilation and errors.
    type the java file and save the file(source file) in the bin folder of ur jdk environment with extension .java. the source file must be the one that has the main method declared.
    in the cmd prompt screen , set the path of bin folder.
    eg:C:/program files/jdk(some version)/bin/...
    for compilation,type:
    javac (source file_name).java and press enter
    for running the file:
    java source file_name

  • Run a UNIX Script from java

    Hi,
    how can i run a unix script from java application. This java application is on windows.
    How can i do this.
    thanks,

    Hi,
    how can i run a unix script from java application.
    This java application is on windows.
    So I think it's safe to assume that the target script is on a remote unix server.
    Take a look at http://sourceforge.net/projects/sshtools/

  • Launching command containing pipe from Java

    Hi,
    i have some troubles to launch a command containing pipe from java.
    I've tried to backslash the pipe but it still not work.
    Maybe someone has an idea about that :
    head -102050 /data/a_very_big_file | tail -5
    the idea is to get 5 lines in the middle of a very big file.
    To launch commands from java i use i think the classical way,
    something like :
    Process p = Runtime.getRuntime().exec(commande[0], this.envp, new File(this.pathExecution));
    I obtain this error :
    ERROR : head: invalid option -- 5
    ERROR : Try `head --help' for more information.
    Thanks for your help,
    kevin.

    kevleb wrote:
    yes same result...
    but i think the problem come from the fact
    that when you pipe your result of a command,
    you launch an other process (is that true).i don't know if another process is launched (the probability is rather high, though)
    but even if that's the case, from the time you rely on a shell and not directly on exec(), i think it shouldn't be a problem to include a | inside the command ; i don't have an idea why it gives you that message error :\

  • Invoking command prompt & executing a java class from one more java class

    Hi,
    I have a problem with my application. I need to develop an editor which compiles and interpretes java programmes. I am develoopping it in Java (Swing and pure Java). I have no problem in compiling a java programme from my editor. But while execuing if any body writes a programme which has console input the system hangs. I am using Runtime.exec() method to call command prompt of Win'2000. My editor is working fine for the programmes written without console input in my editor. I want the same type of input acceptance as JCreator / Vim editors accept.
    How can i achieve this? Please give me some source code help for my requirement.

    When you create a Process object from executing a command you can grab it's input and output streams. Using these, and a text area, you can create a "virtual terminal" for your user to work with their console programs. The rest is just details :)

  • Running command prompt using java

    hi guys,
    i am still quite new to programming. may i know how to run a bat file or command in the background of the application
    without showing the command prompt.
    right now i am able to do it, however it will still pop up the command prompt
    the following is my coding.
    try {
                String command = "cmd /C start C:/project/mkiosk/lib/createMovieJar.bat ";
                Runtime rt = Runtime.getRuntime();
                pr = rt.exec(command);
            } catch (IOException e) {
                e.printStackTrace();
            }

    xclaim wrote:
    ...the following is my coding.
    try {
    Runtime rt = Runtime.getRuntime();
    pr = rt.exec(command);
    ProcessBuilder is a more robust way of creating a Process.
    To avoid problems later, read and implement all the recommendations of [When Runtime.exec() won't|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html] *(<- link).*
    And as an aside, please put a single upper case letter at the start of every sentence. Adding the capital letter helps people to quickly scan the text, looking for ways to help. You would not want to make it harder to help, would you?

  • How to pass Key Event from command prompt to the java application

    If iam running a application that displays JFrame when i pressed CTR+C at the command prompt i.e console window please let me know how can it be passed to the JFrame ie application window

    I doubt that you can pass Ctrl+C to the application since the application is terminated by this key combination.
    You would try adding a WindowListener or may use a shutdown hook to capture the termination of the JVM.

  • Running command prompt commands in java

    I can use:
    Process j = Runtime.getRuntime().exec("command";
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(j.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(j.getErrorStream()));
    to run commands in the command line buf if i make another process..the command will not run...any ideas?

    ProcessBuilder can simplify things:
    redirectErrorStream
    <quote>
    If this property is true, then any error output generated by subprocesses subsequently started by this object's start() method will be merged with the standard output, so that both can be read using the Process.getInputStream() method. This makes it easier to correlate error messages with the corresponding output.
    </quote>

  • Webi document prompts order from Java SDK does not refresh correctly?

    Hi
    I'm developping a standalone command-line Java program which will schedule a report with custom prompt values.
    I am having a problem with Webi prompts ordering acquired from the SDK.
    We are running BO XI R2 SP4 under Windows on Tomcat servers.
    Here is the problem:
    I have a Webi report called "Articles Racines" in a "Tests SDK" directory.
    This report uses two prompts named "Type Article :" and "Code Marque :" (in this order).
    Java SDK (code below) returns the right prompts in the right order.
    Now, in Infoview, I modify the report in order to change the order of the prompts (in the "Properties" tab) making "Code Marque :" the first and "Type Article :" the second one and save the changes.
    When I run the report, prompt order has changed but the prompts retrieved from the Java SDK are still in the old order.
    I noticed that if I update the name of both prompts, the prompts retrieved from the SDK now are in the right order (with the updated names).
    Am I doing something wrong? Is it a known issue?
    Thanks in advance.
    Guillaume
    PS : I am aware that "select *" are very bad but I am still in research stage of developpment.
    TestsScheduler.java:
    import java.util.Iterator;
    import java.util.List;
    import java.util.StringTokenizer;
    import com.businessobjects.sdk.plugin.desktop.webi.IWebi;
    import com.businessobjects.sdk.plugin.desktop.webi.IWebiPrompt;
    import com.crystaldecisions.sdk.exception.SDKException;
    import com.crystaldecisions.sdk.framework.CrystalEnterprise;
    import com.crystaldecisions.sdk.framework.IEnterpriseSession;
    import com.crystaldecisions.sdk.framework.ISessionMgr;
    import com.crystaldecisions.sdk.occa.infostore.IInfoObject;
    import com.crystaldecisions.sdk.occa.infostore.IInfoObjects;
    import com.crystaldecisions.sdk.occa.infostore.IInfoStore;
    public class TestsScheduler {
         public static void main(String[] args) {
              String cms = "XXX";
              String username = "XXX";
              String password = "XXX";
              String authentification = "secEnterprise";
              String reportPath = "/Tests SDK/Liste des racines";
              try {
                   ISessionMgr sessionManager = CrystalEnterprise.getSessionMgr();
                   IInfoObjects objects;
                   // Connexion
                   System.out.println("Connexion à "+ username +"@"+ cms +" ("+ authentification +") en cours...");
                   IEnterpriseSession session = sessionManager.logon(username, password, cms, authentification);
                   System.out.println("Connecté à "+ session.getCMSName());
                   // Récupération de l'infoStore
                   IInfoStore infoStore = (IInfoStore) session.getService("InfoStore");
                   // Récupération des informations d'un report
                   StringTokenizer st = new StringTokenizer(reportPath, "/");
                   int reportID = 0; // Le dossier "Dossiers Publics" est la racine (/)
                   IInfoObjects infoObjects;
                   IInfoObject infoObject;
                   do {
                        String token = st.nextToken();
                        System.out.println("Recherche de l'objet '"+ token +"' en cours...");
                        infoObjects = infoStore.query("select * from CI_INFOOBJECTS where SI_NAME = '"+ token +"' and SI_PARENTID = '"+ reportID +"'");
                        if(infoObjects.size() != 1) {
                             throw new Error("Le dossier SI_ID='"+ reportID +"' possède "+ infoObjects.size() + " fils nommés '"+ token +"'.");
                        infoObject = (IInfoObject) infoObjects.get(0);
                        reportID = infoObject.getID();
                        System.out.println("Trouvé l'objet SI_ID='"+ reportID +"' nommé '"+ infoObject.getTitle() +"'.");
                   } while(st.hasMoreTokens());
                   if(infoObject instanceof IWebi) {
                        IWebi webi = (IWebi) infoObject;
                        List prompts = webi.getPrompts();
                        System.out.println("Le rapport Webi possède "+ prompts.size() +" invite(s).");
                        for(Iterator itPrompts = prompts.iterator(); itPrompts.hasNext();) {
                             IWebiPrompt prompt = (IWebiPrompt) itPrompts.next();
                             List values = prompt.getValues();
                             System.out.println("     L'invite '"+ prompt.getName() +"' possède "+ values.size() +"' valeur(s).");
                             for(Iterator itValues = values.iterator(); itValues.hasNext();) {
                                  Object value = itValues.next();
                                  System.out.println("          Valeur='"+ value +"'.");
                   // Déconnexion
                   System.out.println("Déconnexion en cours...");
                   session.logoff();
                   System.out.println("Déconnecté");
              } catch(SDKException e) {
                   throw new Error("Erreur lors de la connexion : "+ e.getMessage());
    Edited by: Guillaume L on Dec 10, 2008 3:22 PM

    Here's the reason why:
    Web Intelligence document prompting is handled properly if you open the doc using the ReportEngine Java (REBean) SDK.
    When you set prompts and schedule, you'd first open the doc using REBean, set the prompts, then copy over the prompt values you've set to the IWebi you're scheduling using the PromptsUtil.populateWebiPrompts(...,...) helper method.
    So the InfoObject IWebi doesn't know about the actual ordering of the prompts in the document itself - it's just receiving the prompts in order as it's fed from PromptsUtil.
    It's not recommended to assume that the IWebi.getPrompts() will return a non-empty collection.  The Web Intellligence document must be first opened in ReportEngine and the prompting values set using PromptsUtil to fill the collection.
    Sincerely,
    Ted Ueda

  • Run a EXE 'safely' from java

    I want to run a EXE from java code. I did it using Runtime.getRuntime.exec("")...
    but is there a way to prevent the EXE from modifying the files already on the system...I mean the EXE is from a untrusted source......so it may do some malicious activities...is there a way I can stop the EXE from modifying the contents of other files......
    Thanks.

    The people here are volunteers. They post answers for whatever reasons.
    but is there a way to prevent the EXE from modifying the files already on the system...That question has nothing to do with java. Nor really any programming language for that matter. It is an OS question and one that is specific to the OS.
    When an executable is called in java the OS creates another application. Just as if you ran it yourself.
    So the question is whether your OS allows that.
    Given that you said "exe" I presume you mean windows. And that limits your answer to windows users. So you would need a windows user created, which only has read permissions on the system. Then you figure out a windows command that lets you run an application as another user. I am not sure that such an app comes with windows but it if doesn't it can be coded - in C/C++ not java.

  • Running a Linux application from Java

    Hy,
    I am working at a faculty project and I need your help
    What I want to do is by clicking a button, in a JFrame I want to open an application ,for example Mysql Query browser. I am using FC 6 and Netbeans 5.5
    Can you help me??
    Thanks

    can I open the konsole from java??Yes.
    First you must figure out how to do that from the command line yourself. That has nothing to do with java.
    Note that that how you do that MUST account for the fact that the "command line" is actually a shell. Some commands must be run by running the shell as the actual command and then passing the desired command as an option to the shell (the actual command.)
    Again you can google for examples.

  • Command prompt issue from VBscript

    So I have this script that works perfectly for parsing out a COM number and then sending data to said COM port via the command line (things like 'ipconfig > //./COM15'). The issue is that it only works when I use the /K modifier which tells the command
    windows to stay open.  I don't want them to stay open, but whenever I remove the /K, it doesn't work. Nothing gets copied to the COM port. I suspect the cause of this is the command prompt closing before things like systeminfo can finish running. So is
    there a way to have the command prompt window stay open for a short amount of time and then close?
    'Part 1: FindCOM port
    fileName = "C:\rtlstuff\COM.txt"
    Set regex = New RegExp
    regex.Pattern = "COM(\d+)"
    regex.IgnoreCase = True
    regex.Global = True
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set file = fso.OpenTextFile(fileName)
    text = file.ReadAll()
    file.Close
    Dim ComPort
    Set matches = regex.Execute(text)
    For Each m In matches
    ComPort = m.SubMatches(0)
    Next
    'Part 2: Set file dictionary
    set oDic = CreateObject("Scripting.Dictionary")
    oDic.Add 0, "ECHO %DATE% %TIME% > //./COM"
    oDic.Add 1, "ipconfig > //./COM"
    oDic.Add 2, "systeminfo > //./COM"
    v = 3
    'Part 3: Set COM Variables
    Set oShell = WScript.CreateObject ("WScript.Shell")
    MODE = "MODE COM" & ComPort & " 9600,N,8,1,P"
    oShell.run "cmd.exe /C" & MODE
    'Part 4: Data transmission
    Dim Command
    x=0
    do while x < v
    Command = oDic.Item(x) & Comport
    msgbox Command
    oShell.run "cmd.exe " & Command
    x=x+1
    wscript.sleep 10000
    loop

    Can you help me with syntax? I'm still not hugely familiar with VB and I'm not sure how to set this up. This current iteration does not work.
    'Part 1: FindCOM port
    fileName = "C:\rtlstuff\COM.txt"
    Set regex = New RegExp
    regex.Pattern = "COM(\d+)"
    regex.IgnoreCase = True
    regex.Global = True
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set file = fso.OpenTextFile(fileName)
    text = file.ReadAll()
    file.Close
    Dim ComPort
    Set matches = regex.Execute(text)
    For Each m In matches
    ComPort = m.SubMatches(0)
    Next
    'Part 2: Set file dictionary
    set oDic = CreateObject("Scripting.Dictionary")
    oDic.Add 0, "ECHO %DATE% %TIME% > //./COM"
    oDic.Add 1, "ipconfig > //./COM"
    oDic.Add 2, "systeminfo > //./COM"
    v = 3
    'Part 3: Set COM Variables\par
    Set oShell = WScript.CreateObject ("WScript.Shell")
    MODE = "MODE COM" & ComPort & " 9600,N,8,1,P"
    oShell.run "cmd.exe /C" & MODE
    'Part 4: Data transmission
    Dim Command
    i = True
    x=0
    do while x < v
    Command = oDic.Item(x) & Comport
    msgbox Command
    oShell.run "cmd.exe " & Command , ,True
    x=x+1
    wscript.sleep 10000
    loop

  • 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
    }

  • Closing a running windows XP program from java

    Hello,
    Im currently making a program in java under sdk 1.4.0_01 and i want to be able to close a program which is already running in windows(Emule).
    Is this possible?
    I know how to run it using: Process proc = Runtime.getRuntime().exec ("mulePath");
    ...but i dont know how to close it unless ive already run it from java.
    Any help appreciated!
    Craig

    Search the web for the NT Toolkit. It has utilities that you can use to kill a process on NT type os's.

  • Run dial-up connection from Java Program?

    Is there a way to run dial-up connection from a Java Program? It needs to platform independent.
    Thanks.
    Virum

    I very much doubt it, at least not platform independent. I had a, oops, heck of a time doing that from Visual Basic, where it is much easier to work with operating-system stuff like that than it is in Java. I finally ended up buying a RAS component to call from my VB program.

Maybe you are looking for