Runtime.getRuntime().exec and quoted strings?

Attempting to execute a command containing a quoted string. Being very new to Java I'm guessing I'm not doing it right. Below are two code bits the first one works the second doesn't. So the question is "How do I use quoted strings in a command with .exec?"
// this one works
try {               
p = Runtime.getRuntime().exec("ls -l tst.java");
p.waitFor();
System.out.println("Done!");
catch(Throwable e) {                                  
system.out.println("Errors!");
// this one fails
try {               
p = Runtime.getRuntime().exec("ls -l \"tst.java\"");
p.waitFor();
System.out.println("Done!");
catch(Throwable e) {                                  
system.out.println("Errors!");

I don't know if it is too late for the answer, but I think I know what the problem is.
You are using exec(String) method, and passed String parameter is parsed using StringTokenizer class. This means that when you use quotes as in "file1 file2", StringTokenizer parses this as "file1 and then file2" so it is not understandable command.
To solve the problem, do not use exec(String) method, use exec(String[])
Using this you can send separate command and separate parameters as in following example:
If you want to send (in Unix)
grep "SHOW lotid" text.txt
(using exec("grep \"SHOW lotid\" text.txt") would not work)
Do the following
exec(new String[]{"grep", "SHOW lotid", "text.txt"});
This avoids parsing problem when quotes are used.
Mehmed

Similar Messages

  • Runtime.getruntime().exec and text

    I have an application called Truck Scale. This application has a requirement to talk with devices such as a scale indicator, zebra printer, message boards, rf readers and okidata 395 printers. In this application, we have these devices hooked to a serial mux such as a digi and we are using the JAVA COMM API. However, we are having issues with java comm api where all the data that should be transmitted to the port is not being transmitted. We can however transmitt correctly to the port using the unix shell. I would like to forgo using the Java Comm API and execute everything that needs to send or read info for a port via the unix shell. I know I can do this using the runtime.getruntime().exec. However, my issue arises with oki395. The output that needs to be send via the port (not using lp due to overhead of the unix spooler), is formatted text. When I pass the unix command, the formatted text, and my port to the runtime enviornment via the String array, my formatted text loose all of its formatting including newlines. How can I address this issue with the runtime.getruntime().exec.

    Yes, I can send a new line the port correctly from a command line.
    Here is an example of the text file.
    CROSS PLAINS TN 37049 2549
    MATERIAL SPREAD NOT GUARNTEED.NO PERSONAL CHECKS..
    615-654-9942 TOLL FREE 877-654-9942
    Date: 07/21/2009 02:47:31
    Job No: TC1
    Q Num::
    Cust No: 37206728 Src Num::
    Sold To: CROSS PLAINS UNITED METHODIST CHURCH
    Address: 7665 HIGHWAY 25 E
    CROSS PLAINS,TN 37049
    Ord By:
    Ord No: Rate Zone:
    Location: testing changes
    This text is build using a class we created called textTicket which has each line define as a string with the appropriate newlines and tabs on eac line. As soon as this object is added to the string array and is passed to exec to execute the unix command to pipe it out to the port, the textTicket loses its formatting.

  • Runtime.getRuntime().exec() and waitFor on Windows

    Hi,
    I'm trying to execute a command on Windows 2000 using Runtime.getRuntime().exec(). After that I make a call to waitFor method of the returned process instance. The wait for call blocks and never releases. I'm trying to do simple things, like a call to "cmd /c dir", using commands that I know that work and do release after that. I need to wait for the command terminating to get the output just after that.
    Thanks in advance,
    Marcio Azevedo.

    It's too bad ignoring the streams couldn't be build into ProcessBuilder. Instead you could do it yourself and extend ProcessBuilder like:
    public class MyProcessBuilder extends ProcessBuilder {
      private boolean ignoreInputStream;
      public  MyProcessBuilder(List<String> command) {
         super(command);
      public  MyProcessBuilder(String... command) {
         super(command);
      public boolean ignoreInputStream() {
        return ignoreInputStream;
      public  ProcessBuilder ignoreInputStream(boolean ignoreInputStream) {
        this.ignoreInputStream= ignoreInputStream;
        return this;
      public Process start() {
        Process process = super.start();
        if (ignoreInputStream()) {
             new InputStreamIgnorer(process.getInputStream());
        return process;
      static class InputStreamIgnorer implements Runnable {
        java.io.InputStream in;
        InputStreamIgnorer(java.io.InputStream in) {
          this.in = in;
          new Thread(this,"InputStreamIgnorer Thread").start();
        public void run() {
          int ch;
          try {
            while((ch = in.read()) != -1) {
                //System.out.print(ch);
          } catch (java.io.IOException ex) {} //ignore
    }Then it could be simpled used like:
    new MyProcessBuilder("cmd","/c", "dir").redirectErrorStream(true).ignoreInputStream(true).start().waitFor();

  • GetRuntime().exec and wired string

    hello,
    I am trying to use getRuntime().exec in order to run a unix command. everything works fine while i test my code with a command like "pwd" or "ls". But the script i want to run has many special characters. The one that gives me a hard time is >. what can i do for that?
    here is my code:
    <%
         String result = "";
         String line; 
        String test = "ts-query -d test -f ascii \"select ?x where {<http://id.ecs.soton.ac.uk/person/6914> <http://xmlns.com/foaf/0.1/knows> ?x}\"";
        String cmd = "pwd";
        try {
                String[] command = {"/bin/sh", "-c", cmd};
                Process p = Runtime.getRuntime().exec(command);
                BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
                p.waitFor();
                System.out.println("return code: "+ p.exitValue());
                 while ((line = input.readLine()) != null) {
            System.out.println(line);
            result = result.concat(line + " ");
          input.close();
            } catch (IOException e) {
                System.err.println("IO error: " + e);
            } catch (InterruptedException e1) {
                System.err.println("Exception: " + e1.getMessage());
        %>

    First of all thanks a lot for helping me out.
    Well, i have to be doing something really wrong cos when i run this code:
    <%
         String result = "";
         String line;
        try { 
                Process p = Runtime.getRuntime().exec(new String[] {"java", "-server", "-version"});
                BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
                p.waitFor();
                System.out.println("return code: "+ p.exitValue());
                 while ((line = input.readLine()) != null) {
            System.out.println(line);
            result = result.concat(line + " ");
          input.close();
            } catch (IOException e) {
                System.err.println("IO error: " + e);
            } catch (InterruptedException e1) {
                System.err.println("Exception: " + e1.getMessage());
        %>i get no output but when i put the "/bin/sh", "-c", in fronf of the string then i get only the outupt that i would get if i was typing in the terminal "java" and hit return.
    Secondly, the way i understood your reply was to change my original string to lots of arguments in the .exec, something like this:
    Process p = Runtime.getRuntime().exec(new String[] {"ts","-query ","-d ","test ","-f ","ascii"," \"select"," ?x"," where"," {<http://id.ecs.soton.ac.uk/person/6914>"," <http://xmlns.com/foaf/0.1/knows> ","?x}\""});
    well in that case it only runs the "ts" and doesnt do anything else.
    The way i understood it is that every value that is in the String[] is going to be executed individually. like "typing" the first value to the terminal and hit return, then typing the second and hit return e.t.c
    i thought that because i dont get results the fault was that somehow the interpretation of the "<" was mistaken. Am i right?
    again, thanks a lot for your reply! I hope i will make it work with your help.
    p.s in case you are wondering the script i am trying to run has to do with semantic web and rdf querying.

  • Runtime.getRuntime().exec() and Garbage Collection

    I am programming a piece of software in both Java and C that has some strict real time requirements. Garbage collection, which pauses all threads in Java, sometimes causes loss of incoming data. In order to get around this, I am thinking to start another process using Runtime.getRuntime().exec("c_program") and using interprocess controls (in a UNIX environment) to retrieve data from the new process.
    My only worry is that the Process created by the above call would be a child process of whatever JVM thread created it, (as far as I understand, the JVM implementation in Unix uses multiple processes) and would also be paused when garbage collection occurs. Does anyone know the implementation of the exec functionality and the JVM well enough to say that this will or will not happen?
    Thanks in advance,
    Benjamin

    You're going to create a whole new process? I don't
    know what a "child process" means, but Runtime.exec()
    gets the operating system to produce an entirely new
    process, outside the JVM. However if it produces
    output on stdout or stderr, you're going to have
    threads in your JVM that read that output, otherwise
    that process will hang.
    Why is your idea better than just calling the C
    program via JNI?Thank you both for your replies. My plan was to create a whole new process, yes. In UNIX, a process C is created by another process P using fork() or the exec() family. Process P is then the parent of process C, and process C is the child of Process P. P has an amount of control over C since it can send various signals to pause, kill, etc to C.
    My concern was that the JVM implementation would use these signals to implement the pause of all threads before garbage collecting. If it did, it may also pause the Process that it spawned from the Runtime.exec() call. Pausing my C program in this manner would cause the loss of data I was trying to avoid in the first place.
    My plan for the new process was not to produce anything on stdout or stderr, but to pass data back to the JVM using ipc (interprocess communication) resources of UNIX. I would have to use the JNI to access these resources.
    The whole reason for wanting to do this is to avoid the pause during garbage collection that all Java Threads experience. If I were just to call the C program through the JNI with a normal Java Thread as I think you were suggesting, this Java Thread would still be paused during garbage collection.
    To the second reply about RTSJ, I had heard about this but couldn't find info about it! Thanks for the link. I'm checking it out at the moment. The java runtime must be considerably different for the specifications I see that they guarantee.
    Again, thanks for the replies,
    Benjamin

  • Runtime.getRuntime().exec() and java.io.FilePermission

    Hi all.
    I'm trying to run the following code, in an JSP file, inside an Tomcat installation, with Security Manager activated:
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("arp -n -a");But, when I run the JSP, I receive the following error:
    java.security.AccessControlException: access denied (java.io.FilePermission <> execute)I have the following config. file:
    grant {
      permission java.io.FilePermission "/etc/intranet/intranet.properties", "read";
      permission java.io.FilePermission "/home/projetos/Shofar/conf/ShofarParameters.xml", "read";
      permission java.io.FilePermission "arp", "execute";
      permission java.net.SocketPermission "*:5432",   "accept,connect";
      permission java.lang.RuntimePermission  "selectorProvider";
      permission java.util.PropertyPermission "dns.server",        "read";
      permission java.util.PropertyPermission "dns.search",        "read";
      permission java.net.SocketPermission    "*",                 "resolve";
      permission java.net.SocketPermission    "*:53",              "accept,connect,resolve";
      permission java.io.FilePermission       "/etc/resolv.conf",  "read";
      permission java.net.SocketPermission        "127.0.0.1:465",                                                     "resolve,connect";
      permission java.util.PropertyPermission     "user.name",                                                         "read";
      permission java.io.FilePermission           "/usr/lib/jvm/java-1.5.0-sun-1.5.0.06/jre/lib/javamail.providers",   "read";
      permission java.io.FilePermission           "/usr/lib/jvm/java-1.5.0-sun-1.5.0.06/jre/lib/javamail.address.map", "read";
      permission java.security.SecurityPermission "insertProvider.SunJSSE";
      permission java.util.logging.LoggingPermission "control";
      permission java.util.PropertyPermission "java.awt.headless", "read";
      permission java.io.FilePermission "/tmp/-",                  "read,write,delete";
      permission java.io.FilePermission "/var/lib/tomcat5/temp",   "read";
      permission java.io.FilePermission "/var/lib/tomcat5/temp/-", "read,write,delete";
      permission java.io.FilePermission "/var/lib/tomcat5/work/-", "read,write,delete";
      permission java.util.PropertyPermission "java.io.tmpdir",    "read,write";
      permission java.lang.RuntimePermission "accessClassInPackage.sun.util.calendar";
      permission java.lang.RuntimePermission "accessDeclaredMembers";
      permission java.lang.RuntimePermission "suppressAccessChecks";
      permission java.lang.RuntimePermission "accessClassInPackage.org.apache.jasper";
      permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
    };As seen, I put the permission java.io.FilePermission "/usr/sbin/arp", "execute"; line, but it don't work.
    What I need to put in the file?

    paulcw is right on the money on that one. You can easily create a bat file to perform that operation for you. However if you are feeling a little adventurous you can always use a Process:
    Process process=Runtime.getRuntime().exec(.....);
    int oneChar;
    InputStream inputStream=process.getInputStream();
    File file=new File("test.txt");
    try{
    file.createNewFile();
    } catch (Exception e){}
    FileOutputStream outputStream=new FileOutputStream(file);
    while ((oneChar=inputStream.read())!=-1){
    outputStream.write(oneChar);

  • Runtime.getRuntime().exec() and rewind of stdin

    Hello-
    I have a need to use exec() to call a process that takes it's inputs on stdin, and outputs to stdout and stderr. On simple test cases, this all works fine with proc.getErrorStream(), proc.getInputStream(), and proc.getOutputStream(), with data being passed with BufferedReaders and BufferedWriters.
    However, my program (written in fortran) takes the stdin it receives and rewinds it (rewind 5) after reading through it once. This causes my program to crap out when I flush my OutputStream. If i don't flush / close the OutputStream, my program deadlocks. Any idea what to check for?
    Here's my class that i call:
    class InWriter extends Thread {
      OutputStream os;
      String in;
      BufferedWriter out;
      public InWriter(OutputStream os, String input){
         this.os = os;
         this.in = input;
      public void close(){
         try{
           out.flush();
           out.close();
         }catch(Exception e){
           System.out.println("Error when trying to close stdin stream:");
           e.printStackTrace();
      public void run(){
            try {
           int write = 1024;
           System.out.println("input length: " + input.length());
           out = new BufferedWriter(new OutputStreamWriter(os), write);
             out = new BufferedOutputStream(os, write);
           int wrote = 0;
           int left = 0;
             while(wrote < input.length()){
              left = input.length() - wrote;
              if(left < write){
              out.write(inputB, wrote, left);
              else{
              out.write(inputB, wrote, write);
              wrote += write;
           close();
           catch(Exception e){
          System.out.println("Error writing to stdin");
          e.printStackTrace();
    }any info greatly appreciated!
    -Ed

    tkleisas: the process is crapping out when I call flush()
    BIJ : I would think a stream is NOT inherently rewindable / un-seekable, since you can mark and reset InputStreams. As a workaround, I am currently writing an intermediate file, and calling the fortran program with file redirection (i.e. "cmd /C myprogram < inputfile"), which works fine, but we would prefer not to have to do it this way.
    I've also tried different ways to write out via a FileChannel, but I can't seem to sync up FileDescriptor.in and the outputstream I get from the process.
    byte[] inputB = input.getBytes();
    ByteBuffer bb = ByteBuffer.allocateDirect(input.length());
    Bb.put(inputB, 0, input.length());
    FileOutputStream fs = new FileOutputStream(FileDescriptor.in);
    FileChannel fc = fs.getChannel();
    int numBuffersNeeded = (input.length() / write) + 1;
    ByteBuffer[] bbs = new ByteBuffer[numBuffersNeeded];
    wrote = 0;
    left = 0;
    byte[] tempb = new byte[write];
    ByteBuffer tempB = ByteBuffer.allocateDirect(write);
    for(int i = 0; i < numBuffersNeeded; i++){
           left = input.length() - wrote;
           //System.out.println("left: " + left);
           //System.out.println("Writing " + i + " of " + numBuffersNeeded);
           if(left < write){
                System.arraycopy(inputB, (i * write), tempb, 0, left);
           else{
                System.arraycopy(inputB, (i * write), tempb, 0, write);
           tempB = ByteBuffer.allocateDirect(write);
           tempB.put(tempb, 0, write);
           bbs[i] = tempB;
           wrote += write;
    //FileDescriptor.in.sync();
    //System.out.println("bb length: " + bb.length);
    //fc.write(bb);
    //bb.rewind();
      fc.write(bbs);
      fc.close();
      fs.close();

  • Runtime.getRuntime().exec() and waitFor()

    I have a problem where waitFor doesn't work as it should due to the fact that cmd.exe really did terminate.
    I'm executing a
    cmd.exe /c c:\abc.xml
    the xml is a word document, the cmd.exe will terminate, and word will open. I need to somehow keep the cmd.exe opened so the waitFor doesn't just finish.
    If I do cmd.exe /c c:\abc.doc, the word will open under cmd.exe, hence cmd.exe doesn't terminate, it's just this xml case.
    Someone enlighten me.
    thx

    Well because I don't know if that xml is just a text xml or a word xml...
    doing cmd /c whatever.xml will let the computer decide what it is and open the appropriate application to read it. But for some reason cmd terminates after opening that determined software, while if I do something like cmd /c whatever.DOC it'll open word under the cmd process and cmd won't terminate.

  • Problems with Runtime.getRuntime().exe and getting output. Please Help me!!

    I'm creating a program that runs the followings programs written in C and compiled with gcc:
    ==========================The first C program====================================
    #include<stdio.h>
    void leia();
    main()
    int x = 20;
    int y = 2;
    printf( "Marcinho e Danny\n" );
    printf( "Te\n" );
    printf( "Vida\n" );
    printf( "Marciorja: %d.\n", x * y );
    ===============================================================================
    ==========================The second C program====================================
    #include<stdio.h>
    void leia();
    main()
    int x = 20;
    int y = 2;
    printf( "Marcinho e Danny\n" );
    printf( "Te\n" );
    printf( "Vida\n" );
    printf( "Marciorja: %d.\n", x * y );
    scanf( "%d", &x ); //This is the statement added to the latter C program.
    ===============================================================================
    I compiled this C program and generates the a.exe program. I have the following Java program:
    ==================================================================================
    import java.awt.Color;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.util.StringTokenizer;
    import javax.swing.JFrame;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.EditorKit;
    import javax.swing.text.MutableAttributeSet;
    import javax.swing.text.Style;
    import javax.swing.text.StyledDocument;
    import javax.swing.text.StyledEditorKit;
    public class Teste
    private BufferedWriter out;
    private BufferedReader in;
    private Style stylePrompt;
    private LeitorDeEntrada le;
    private String entrada = "";
    private AreaDeEdicao areaDeTexto;
    Process p = null;
    public Teste( AreaDeEdicao areaDeTexto )
    this.areaDeTexto = areaDeTexto;
    public void runCommand( String command ) throws IOException
    StringTokenizer strTokenizer = new StringTokenizer( command );
    String mainCommand = null;
    String argument = null;
    StyledDocument doc = areaDeTexto.getStyledDocument( );
    String[] prefix = new String[] { "cmd.exe", "/c", command };
    p = Runtime.getRuntime().exec( prefix, null, new File( System.getProperty( "user.dir" ) ) );
    in = new BufferedReader( new InputStreamReader( p.getInputStream( ) ) );
    out = new BufferedWriter( new OutputStreamWriter( p.getOutputStream( ) ) );
    out.flush();
    Thread t = new Thread( )
    public void run( )
    super.setName( "Marcio" );
    execute( );
    public void execute( )
    String c = null;
    try
    if( !in.ready( ) )
    try
    this.sleep( 1000 );
    catch( InterruptedException e2 )
    e2.printStackTrace( );
    System.out.println( "in.rea: " + in.ready( ) );
    c = in.readLine( );
    catch( IOException e )
    e.printStackTrace( );
    String str = "";
    while( c != null )
    str = c + "\n";
    try
    areaDeTexto.getDocument( ).insertString( areaDeTexto.getDocument( )
    .getLength( ),
    str, null );
    catch( BadLocationException e3 )
    e3.printStackTrace( );
    try
    c = in.readLine( );
    catch( IOException e2 )
    e2.printStackTrace( );
    areaDeTexto.setCaretPosition( areaDeTexto.getDocument( )
    .getLength( ) );
    try
    in.close( );
    catch( IOException e1 )
    e1.printStackTrace( );
    t.setDaemon( true );
    t.start( );
    le = new LeitorDeEntrada( );
    areaDeTexto.addKeyListener( le );
    public static void main( String[] args )
    JFrame janela = new JFrame( );
    AreaDeEdicao areaDeTexto = new AreaDeEdicao( new MyDocument( ) );
    areaDeTexto.setBackground( Color.black );
    areaDeTexto.setForeground( Color.GREEN );
    janela.getContentPane( ).add( areaDeTexto );
    Teste teste = new Teste( areaDeTexto );
    try
    teste.runCommand( "a.exe" );
    catch( IOException e )
    e.printStackTrace( );
    janela.setSize( 500, 300 );
    janela.setVisible( true );
    class LeitorDeEntrada extends KeyAdapter
    public void keyPressed( KeyEvent e )
    char c = e.getKeyChar( );
    System.out.println( "keyPressed" );
    try
    if( c == '\n' )
    areaDeTexto.getDocument().insertString( areaDeTexto.getDocument( )
    .getLength( ),
    c + "", null );
    out.write( c + "" );
    out.flush();
    catch( BadLocationException e2 )
    e2.printStackTrace( );
    } catch (IOException e2) {
    e2.printStackTrace();
    ==================================================================================
    This Java program is very simple. It runs the a.exe using the method Runtime.getRuntime().exec and gets input for a.exe from a JTextPane and shows the output in the same JTextPane.
    If my a.exe represents the binary code of the first C program the text in the JTextPane is the correct output of the a.exe. But, if my a.exe represents the binary code of the second C program, the JTextPane shows the messages ( "Marcinho e Danny\n", "Te\n", "Vida\n", "Marciorja: %d.\n") after I enter the value claimed by the scanf.
    I tested my Java program running programs that require input and all have the same behavior:.
    What can I need to do to solve this bug?
    I read other posts with the same problem and nobody answers what is the problem.
    I'LL pay 10 Duke dollars to the first that answers me.

    The second C program with the statement fflush( stdout ) produces the right output.
    #include<stdio.h>
    void leia();
    main()
    int x = 20;
    int y = 2;
    printf( "Marcinho e Danny\n" );
    printf( "Te\n" );
    printf( "Vida\n" );
    fflush( stdout ); //added statement.
    printf( "Marciorja: %d.\n", x * y );
    scanf( "%d", &x ); //This is the statement added to the latter C program.
    but what can I do to run C programs that doesn't flush the stdout?

  • Wierdness w/ Runtime().getRuntime().exec between 8.1.6 and 8.1.7

    A Java SP that executes OS commands runs fine in 8.1.6, but doesn't run in
    8.1.7 when a window is generated as a result of the call. The Java class
    follows:
    package com.crtinc.oracle.util.osrun;
    import java.io.*;
    public class SimpleRunner extends Object {
    //just run the daggone command, don't worry about any errors, feedback,
    etc...
    public static void run(String cmd) throws IOException {
    Runtime.getRuntime().exec(cmd);
    The call spec follows:
    CREATE OR REPLACE PACKAGE SIMPLERUNNER AUTHID CURRENT_USER AS
    PROCEDURE RUN ("cmd" IN VARCHAR2)
    AS LANGUAGE JAVA
    NAME 'com.crtinc.oracle.util.osrun.SimpleRunner.run(java.lang.String)';
    END SIMPLERUNNER;
    When deployed to v8.1.6 by a user with JAVASYSPRIV, the following call from
    SQL*Plus runs and displays a window:
    exec simplerunner.run('notepad.exe');
    When deployed to v8.1.7, the same call causes notepad.exe to be added to the NT
    Task Manager Processes tab, but the notepad window doesn't actually open up.
    FWIW, the above code is a simple example - myactual utility captures the
    output streams of OS commands, very much along the lines of sample code that
    I've seen on Metalink - this also works fine in 8.1.6, but never returns in
    8.1.7.
    Granted, running Notepad is of limited utility (though it demos very well :-),
    but other useful OS commands that spawna window (such as kicking of an Oracle
    Report, which pops up a small status window) do not run now in 8.1.7. Running
    a completely non-visual process seemsto work fine, however.
    Any help much appreciated!
    Thanks
    Jim

    Well, just for anyone who might be facing such an issue in the future...
    I am running the databse on NT and it turns out that my NT service didn't have the 'Allow Service to Interact with Desktop' checkbox selected, so that's why OS commands that generated windows weren't showing up. Checking that checkbox and stopping/restarting the service solved the problem.
    Jim
    null

  • Runtime.getRuntime().exec hangs and doesn't print the output

    Hi,
    I have written the following code to execute the command "psexec ipaddress -u userid -p password -l -c execute.exe >> c:/25_showoutpout.txt" and print the output in 25_showoutpout.txt file.
    import java.io.*;
    public class ExecTest{
         public static void main(String args[]) throws IOException{
         String args1 = "psexec ipaddress -u userid -p password -l -c execute.exe >> c:/25_showoutpout.txt";
         try{
         Process p=Runtime.getRuntime().exec(args1);
    int i = p.waitFor();
         System.out.println("Done.with time "+i);
         }catch(Exception e){
              System.out.println("The error is "+e);
    But this program hangs and creates a blank 25_showoutpout.txt file.In the process list I can see the process running, but it doesn't redirect the output in the txt file.When i run the command from the command line it runs fine.Please help me.
    Thanks in advance

    Hi,
    I have written the following program to get the output.But still the required output is not coming in the console file.Only the messages that gets printed in the parent console that is coming in the file.But the expected output is to get the messages from the child window which gets executed while the .exe runs.
    import java.io.*;
    public class RuntimeExecTest{
    public static void main(String args[]){
    String s = null;
    String result= null;
    int count =0;
    try{
              // read the output from the command
    String cmd = "cmd.exe /c D:/installer/PsTools.zip/PsTools/psexec.exe ipaddress -u userid -p password -l -c excute.exe >> C:/RuntimeExec_25.txt";
         Process p = Runtime.getRuntime().exec(cmd);
         InputStream is = p.getInputStream();
         // Get the std in to the process.
         OutputStream os = p.getOutputStream();
         // Get the std err from the process.
         InputStream es = p.getErrorStream();
         // Create readers for those streams.
         BufferedReader reader = new BufferedReader(new InputStreamReader(is));
         BufferedReader errReader = new BufferedReader(new InputStreamReader(es));
         String line;               
         // Read STDOUT into a buffer.
         // If no STDOUT check STDERR.
         while((line = errReader.readLine()) != null){
              // Do something with data here if you wish.
         System.out.println( line );
         while((line = reader.readLine()) != null){
              // Do something with data here if you wish.
         System.out.println( line );
         System.exit(0);
    catch( Exception ex )
    ex.printStackTrace();
    }

  • Runtime.getRuntime().exec(...) problems and exit codes

    Hi,
    I am trying to launch an application 4 times with different arguments from a Java app. I have tried doing it sequentially and in four different threads, but the results are the same: sometimes the 4 of them are properly launched, sometimes (the most of the times) only 3 are launched and sometimes only 2. I have tried with cmd and cmdarray[] as parameters for exec but the results are the same.
    This is one of the four threads I use:
    Runnable r1 = new Runnable(){
                        public void run(){
                             String ecgCommand = "./flute -S -m:" + Config.ECGS_FLUTE_IP + " -p:" + Config.ECGS_FLUTE_PORT + " -F:" + Config.ECGS + " -r:" + Config.ECGS_FLUTE_RATE + " -C";
                             System.out.println(ecgCommand);
                             InputStream ecgsStream = null;
                             InputStreamReader isr = null;
                             BufferedReader br = null;
                             try{
                                  ecgsProcess = Runtime.getRuntime().exec(ecgCommand, null, new File(Config.HOME_PATH + Config.FLUTE_PATH));
                                  String line;
                                  ecgsStream = ecgsProcess.getInputStream();
                                  isr = new InputStreamReader(ecgsStream);
                                  br = new BufferedReader(isr);
                                  StyledDocument styleDoc = mm.ecgFluteMessages.getStyledDocument();
                                  Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
                                  while((line = br.readLine()) != null && running){
                                       if(styleDoc.getLength() > 25000)     mm.ecgFluteMessages.setText("");
                                       styleDoc.insertString(styleDoc.getLength(), line+ "\n", def);
                                       mm.ecgFluteMessages.setCaretPosition(mm.ecgFluteMessages.getDocument().getLength());
                                  System.out.println(ecgsProcess.waitFor());
                             }catch(Exception e){
                                  try {
                                       br.close();
                                       isr.close();
                                       ecgsStream.close();
                                  } catch (Exception e1) {
                                       e.printStackTrace();
                   new Thread(r1).start();Adding a Thread.sleep between runnables doesn't have any effect.
    In addition, those processes that are not properly launched return an exit value of 255. I have searched for its meaning but I have found nothing. Could anybody tell me where can I find a list of the JVM exit codes in order to guess what is happening?
    Can anybody help me with this issue? Help is much appreciated.
    Thanks a lot

    I have been looking for it but it seems it has not any exit code list or any documentation regarding this. Anyway, I think 255 is a JVM error code (the last one, errors are numbered in modulo 256) which means that the error has nothing to do with JVM but with the application execution (flute in my case).
    I have added a prompt for the errorStream and I have this message for the 255 exited programs:
    not well-formed (invalid token) at line 15+
    And the four commands are like this:
    *./flute -S -m:239.255.255.253 -p:60102 -F:./ecgs -r:150 -C*
    *./flute -S -m:239.255.255.252 -p:60103 -F:./ads -r:150 -C*
    *./flute -S -m:239.255.255.251 -p:60104 -F:./pushvod -r:50 -C*
    *./flute -S -m:239.255.255.250 -p:60105 -F:./banners -r:150 -C*
    So, as the process is sometimes initialized properly and others it is not, it seems that there is a problem with the tokenizing of the command not happening always. As I have tried it with a single command line and with an array of command strings (the first for "./flute" and the followings for each argument) with the same results I can't understand why is this problem happening sometimes. Happening always would help me in giving a clue but that's not the case.
    Any idea? Thanks a lot.
    Edited by: dulceangustia on Apr 3, 2008 3:41 AM

  • Swign application and Runtime.getRuntime().exec(cmd)

    i want to use this program in a swing application, when i press the button it will execute this comand,?? is possible?
    String[] cmd = {"pwd","ls"};
    try {
    Process ls = Runtime.getRuntime().exec(cmd);
    BufferedReader input1 = new BufferedReader(new InputStreamReader(ls.getInputStream()));
    String str = input1.readLine();
    /* Keep looping until we have read all of the output */
    while(str != null) {
    System.out.println(str);
    str = input1.readLine();
    } catch (java.io.IOException el) {
    System.err.println(el);
    import javax.swing.*;
    import java.awt.event.*;
    public class Main{
    JFrame frame;
    public static void main(String[] args){
    Main db = new Main();
    public Main(){
    frame = new JFrame("Show Message Dialog");
    JButton button = new JButton("Click Me");
    button.addActionListener(new MyAction());
    frame.add(button);
    frame.setSize(400, 400);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    public class MyAction implements ActionListener{
    public void actionPerformed(ActionEvent e){
    JOptionPane.showMessageDialog(frame,"hello");
    }

    its pretty hard to read without code tags,
    if your questions is can i use this code in my new swing applications when i press a button
    sure you can you need to make your new program with actionlisterners, your button will then wait until you click on it,
    then you will call your old method when the button is clicked
    I think that what you want sorry if i got the wrong end of the stick

  • Runtime.getRuntime().exec(java method); - Passing strings between methods

    Hi all,
    I am using Runtime.getRuntime().exec(java xxxxxx); to run a java program from within a java program, i also need to pass a string to the new program. Does anyone know how to do this?
    Matt

    how would i retrive those strings in myApp as i want
    to put the values from them in a JLabelYou have a main method like this, right?
    public static void main(String[] args) { ... }
    args contains the array of strings passed to the app from the command line.

  • Runtime.getRuntime().exec at JBuilder

    I�m gonna show you the interest part of the program:
    void jButton13_actionPerformed(ActionEvent e)
    try
    Process p = Runtime.getRuntime().exec(d:\\jmonrubia\\AWouter\\CntVirRel.exe");
    System.out.println("Procesando.....");
    int valorRetorno = p.waitFor();
    System.out.println("Acabado");
    catch(InterruptedException lop){lop.printStackTrace();}
    catch(IOException ds){ds.printStackTrace();}
    catch(IllegalThreadStateException ds){ds.printStackTrace();}
    catch(Throwable t){t.printStackTrace();}
    Beeing the result at the System.out:
    Procesando.....
    Exception! File: handler.cpp, Line: 73
    Invalid filename.
    Acabado
    The exe file doesn�t do anything. The handler.cpp is a library which the exe file use.
    But in a Example.java using JDK (javac Example.java and
    later java Example) like this:
    import java.io.*;
    public class Example
    public static void main (String args[]) throws IOException
    Process proc = Runtime.getRuntime().exec("CntVirRel.exe");
    try
         System.out.println("Empieza a esperar");
         proc.waitFor();
         System.out.println("Acaba la espera");
    catch (InterruptedException e){}
    Then here the exe file works, so ... I don�t understand why.
    Here, the program run so I don�t understand why at JBuilder say
    something about the handler.cpp.
    I hope that with this you can understand something.
    Thank you.

    check the line..
    Process p = Runtime.getRuntime().exec(d:\\jmonrubia\\AWouter\\CntVirRel.exe");
    [\code]
    there's a missing quote..in the command string

Maybe you are looking for

  • Error in transpoting info object

    Hello, Need help to solve this please! I am getting an error while tranporting an info object! Error 1 with function module RSDRX_FILL_INITIAL_PQTABLE (Fill Master Data) Message no. R7195 Diagnosis Possible causes: Function module DB_CREATE_TABLE The

  • My iPad 4 is needed 4.1 GB free space

    i tried to install iOS 7 ,that capacity 1.4 GB it's ok but device is needed 4.1 GB free space , why was that? if any one can give clear information to me ,it may be reason for i'm using alot of applications?

  • When on Develop tab Photo has white colour with red splotches???

    Hey guys so I get this strange thing happening when I click on the develop tab in Lightroom. I have created a new catalog, imported some photos and on the library tab everything looks good. But when I click on the develop tab I see red all over what

  • OS 10.9.3 Screen freezes

    Since installing OS 10.9.3 update yesterday my sceen has partiall locked up three times forcing a reboot each time. The lockup comes without warning sometimes in the middle of a curser move.  The main screen locks up in the sense that the cursor move

  • Where has the 'Info' section gone in the sync screen?

    The summary page of my iPhone when viewed in iTunes no longer shows the "Info" category. Do I restore this through settings or is this a post upgrade version glitch that Apple need to attend to?