Java.lang.Process output stream problem

Hi, I have a program that starts a process (java.lang.Process) using the java.lang.Runtime.exec() and it attemtps to interface with it using the provieded io streams. I have both the output and error streams being handled on their own threads and I have a hashmap of output lines/command pairs that are checked so that when the process outputs certain lines to the console it feed the proper input into the process. My problem is that when I feed the input into the process it dosen't respond to it almost like the user hasn't pressed enter, The process hangs. I have tried using /n /r and permutations thereof but nothing works. The thread does read the lines from the process and does output to the process from what i can gather. Can you help me!
here is some of the code..
public void run() {
try {
     //the process's output
     InputStreamReader isrOutput = new InputStreamReader(inOutput);
     //the process's input(our output)
     PrintWriter pw = new PrintWriter(outInput);
     String line = null;
     while(true){
          if(brOutput.ready()){
               line = "";
               while(brOutput.ready())
     line+=(char)brOutput.read();
               System.out.print(line);
               if(commands.containsKey(line)){
     pw.println((String)commands.get(line));
     System.out.println((String)commands.get(line));;
} catch (IOException ioe) {
          ioe.printStackTrace();
}Thanks

Oops.. i forgot to flush my PrintWriter /blushing......... Thanks

Similar Messages

  • Java.lang.IllegalStateException : output stream already retrived Error

    Hi All
    I am trying to integrate crystal reports 10g with oracle 10g AS.My application works fine on TOMCAT 4.1.31,but when I depoly in oracle 10G AS,it shows the following exception
    Java.lang.IllegalStateException : output stream already retrived.
    Any suggestions?
    Regards
    Mohan

    Hello,
    Awaiting help.
    Thanks and Regards
    Mohan

  • Java.lang.IllegalStateException : output stream already retrived.

    Hi All
    I am trying to integrate crystal reports 10g with oracle 10g AS.My application works fine on TOMCAT 4.1.31,but when I depoly in oracle 10G AS,it shows the following exception
    Java.lang.IllegalStateException : output stream already retrived.
    Any suggestions?
    Regards
    Mohan

    Hello,
    Awaiting help.
    Thanks and Regards
    Mohan

  • Java.lang.Process input stream waiting until process is complete to print

    I have tried to simplify this problem as much as possible. Basically, I have a java.lang.Process which executes a simple C program.
    test.c
    #include <stdio.h>
    #include <unistd.h>
    int main()
      printf("foo\n");
      sleep(2);
      printf("bar\n");
    ...The process has an input stream and error stream handler each on a separate thread. I have tried both buffered and unbuffered (BufferedReader, BufferedInputStream, InputStreamReader...) stream handlers. Both produce the same problem of waiting until the process has exited to receive anything from the process's streams.
    The only time this does not happen is when I call fflush(stdout); after each printf(). This can't be a solution because the real application calls a massive C application which would require thousands of fflush()'s to be added. What is causing this to happen? This doesn't happen when the C program is executed from the shell. Is there a way the InputStream can be forced to extract from the stream?

    hi.....
    I have closed the output stream of the process as you told me to do...
    The hitch is that, if my program contains only printf() statements,it works fine
    as soon as scanf() statement is encountered within the C code,it is totally neglected,and the output comes as if no scanf() statement existed in the C code.
    Consequently the thread doesnt wait for input which was bound for scanf() from the thread
    the code...
        public void run()
         try
             PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
             BufferedReader in = new BufferedReader(
                            new InputStreamReader(
                            socket.getInputStream()));
             try
                     Process p;
              p=new ProcessBuilder("./a.out").start();
                     PrintWriter exOut=null;
                     BufferedReader exIn=null;
              exOut = new PrintWriter(p.getOutputStream(),true);
              exIn = new BufferedReader(
                           new InputStreamReader(
                           p.getInputStream()));
                  //String inputLine="", outputLine="";        
                  String str="";
                     int c;          
                  while(true)                   
                        //System.out.println("In While");
                  str="";exOut.close();                  
                        while((c=exIn.read())!=-1)
                                 str=str+(char)(c);
                                    System.out.print(str);
                        str=str+(char)(0);
                        System.out.print(str+"outside");
                        out.print(str);
                        sleep(100);
                        try
                            int x=p.exitValue();
                              out.print(str);
                   System.out.print("Bye 1");
                            String str1="Bye"+(char)(0);
                   out.println(str1);              
                   break;
                        catch(IllegalThreadStateException e)
                            //System.out.println("The Process has not ended yet");
                        //str=str+((char)-1);
                        //System.out.print(str+"Control reaches here too");
                        str="";
                        exOut = new PrintWriter(p.getOutputStream(),true);//I have tried to run the program without this also but the effect is the same
                        while((c=in.read())!=-1)
                            str=str+(char)(c);                                    
                        if(str.contentEquals(""))
                                System.out.print("Bye 2");
                                String str1="Bye"+(char)(0);
                                out.println(str1); 
                                p.destroy();
                                exOut.close();
                                exIn.close();
                                out.close();
                                in.close();        
                                socket.close();
                                break;
                        //str=str+(char)(0);
                  exOut.print(str);
                        try
                            int x=p.exitValue();
                            System.out.print("Bye 3");
                            String str1="Bye"+(char)(0);
                   out.println(str1);
                            break;
                        catch(IllegalThreadStateException e)
                            //System.out.println("The Process has not ended yet");
                  /*while ((inputLine = in.readLine()) != null)
                        exOut.println(inputLine);
                        outputLine=exIn.readLine();
                        //outputLine=inputLine;
                        //out.println(outputLine);}*/                   
             exOut.close();
             exIn.close();
             catch(IOException e)
                  System.err.println("Accept failed."+e);
             out.close();
             in.close();        
             socket.close();
         catch (Exception e)
             e.printStackTrace();
    }

  • Get complete output from java.lang.Process

    How do I get the complete output from java.lang.Process?
    By the time I've started reading from Process.getInputStream() the process has already terminated...

    I solved the problem:
    private int exec(String pArguments[], OutputStream pOut, OutputStream pErr) throws IOException {
         class ProcessOutputPrinter implements Runnable {
              private InputStream ivIn;
              private OutputStream ivOut;
              public ProcessOutputPrinter(InputStream pIn, OutputStream pOut) {
                   ivIn = pIn;
                   ivOut = pOut;
              public void run() {
                   try {
                        for(int tByte; (tByte = ivIn.read()) != -1; ) {
                             ivOut.write(tByte);
                        ivOut.flush();
                   catch(IOException e) {
                        e.printStackTrace();
         // Start process
         Process tProcess = Runtime.getRuntime().exec(pArguments);
         // Create out printer
         Thread tOutPrinter = new Thread(new ProcessOutputPrinter(tProcess.getInputStream(), pOut), "NamingAdmin out-printer");
         tOutPrinter.start();
         // Create err printer
         Thread tErrPrinter = new Thread(new ProcessOutputPrinter(tProcess.getErrorStream(), pErr), "NamingAdmin err-printer");
         tErrPrinter.start();
         // Wait for process and printers to finish
         try {
              tProcess.waitFor();
              tOutPrinter.join();
              tErrPrinter.join();
         catch(InterruptedException e) {
         // return process exit value
         return tProcess.exitValue();

  • Problem with starting a sqlplus-process via java.lang.Process

    Hi,
    I want to start a sqlplus-Process from a java-application via java.lang.Process. Works great with XP. On a W2K-Machine, the process is started (I can see it in the Taskmanager), but it doesn't connect to the db - the OS-process hangs, also the java-application which invoked the process.
    If I start a sqlplusw.exe-Process instead of sqlplus.exe, it works as well.
    Does anybody know what's going wrong ?
    I'm using java 1.5.0_11 and Oracle Database 10g Enterprise Edition Release 10.2.0.3.0
    Thanks in advance
    Jens

    java.lang.Process can be used to perform an OS Shell to launch specific tasks. But why are you interested in specifically launching sqlplus from here?
    ~ Madrid
    http://hrivera99.blogspot.com/

  • Problwm with java.lang.Process

    I am using java.lang.Process to read the output of a command, it works fine with one word commands such as "ls", but a command with a pipe and and arguments returns no output, for example "who | grep root".
    Any ideas!

    for example "who | grep root".
    Any ideas! Probably because you really should have nothing returned. Try to give the output of the first command as an input to the second one but not through a pipe; use java.lang.Process twice.

  • Java.lang.process.execute()

    Java.lang.process.execute() is throwing an exception with string �Cannot allocate memory� ...
    what is the cause of this exception and give me the solution
    plz help
    Nilesh

    882590 wrote:
    Is it possible to use the java.lang.ProcessBuilder to execute a Java process pointing it to jvm.dll instead of java.exe? I'm using the JavaFX self contained application packaging and it creates a runtime/jre/bin directory that contains jvm.dll, but not java.exe.I don't get the line of questioning of this thread. If you're using the JavaFX stuff the answer must lie in the JavaFX documentation. It seems to indicate that it generates an executable of its own which will likely wrap the jvm DLL, so you should be invoking the generated executable in ProcessBuilder.
    http://docs.oracle.com/javafx/2/deployment/self-contained-packaging.htm

  • Java.lang.Process.exec()

    I have read a article about the "java.lang.Process.exec()" (url:http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html)
    Having some questions with the example in it.
    The example code:
    import java.util.*;
    import java.io.*;
    public class BadExecJavac
        public static void main(String args[])
            try
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec("javac");
                //int exitVal = proc.exitValue();
                int exitVal = proc.waitFor();
                System.out.println("Process exitValue: " + exitVal);
            } catch (Throwable t)
                t.printStackTrace();
    }The process can run but never complete.
    Why? Just because when invoke the javac.exe without any argument,it will product a set of usage statements that describe how to run the program and the meaning of all the available program options.So the process is in deadlock.
    The question is, when i change the exec("javac") to exec("javac a.java"), in which the "a.java" is not exist, so the jvm should product error:
    error: cannot read: a.java
    1 error
    But after i changed the code and run the class, at this time the process can run and complete.
    The two codes both product some statements,but why the first one never complete,but the second did. Why?

    import java.util.*;
    import java.io.*;
    public class A
        public static void main(String args[])
            try
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec("javac");
                InputStream is = proc.getErrorStream();
                int i=0;
                while ((i = is.read()) != -1)
                    System.out.print((char)i);
                // int exitVal = proc.exitValue();
                // int exitVal = proc.waitFor();
                // System.out.println("Process exitValue: " + exitVal);
            } catch (Throwable t)
                t.printStackTrace();
    }usng this modification, i could see some error messages.
    because exec(cmd) executes the command in a separate process, it will not display the results on the current console. If you want see the results, you should use getInputStream() and getErrorStream().
    good luch ^^

  • Exception in thread "main" java.lang.Error: Unresolved compilation problem

    The following code:
         public boolean find(MusbachJ_Person person,BstNode node)
              //p.l(person);p.l(node.intData);
              if(node.intData.compareTo(person)==0)
                   return true;
              if( node.leftNode != null ) find(person,node.leftNode );
              if( node.rightNode != null ) find( person, node.rightNode);
              else
                   return false;
         }returns the following compilation error:
    Exception in thread "main" java.lang.Error: Unresolved compilation problem:
         This method must return a result of type boolean
         at MusbachJ_TreeNode.find(MusbachJ_TreeNode.java:32)
         at MusbachJ_PeopleTree.main(MusbachJ_PeopleTree.java:91)
    But I don't understand, the else statement is right there, what more does it want? Thanks! :)

    John_Musbach wrote:
    Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unresolved compilation problem is an error that you'll only ever see if you're using an IDE. If you used the javac compiler, then you would have seen that the code doesn't even compile.
    The reason (as others have pointed out) is, that some paths through your method don't return a value.
    I'll re-write your code in the code-style that I usually use, because then it might be easier for you to see the problem:
    public boolean find(MusbachJ_Person person,BstNode node)
         if(node.intData.compareTo(person)==0) {
              return true;
         if( node.leftNode != null ) {
              find(person,node.leftNode );
         if( node.rightNode != null ) {
              find( person, node.rightNode);
         else {
              return false;
    }There are two prolbems. I'll spell out the first and let the other one for you to find:
    1.) you don't do anything with the return-values of the find-methods you are calling. What do you want to do with them?
    2.) What do you return if the current node is not the one that you want and you've got a right node?

  • [java.lang.Process] Howto simulate ENTER ?

    Hi there!
    I need to control an interactive command-line tool from java (smbclient) and for this task I use Process with getOutputStream().
    However I want to send commands to the native-program like: Process.getOutputStream.write("exit\n".getBytes()) but it simply does not work :-(
    I think the native programs does not recognize the "\n" as <ENTER> .
    Any ideas howto solve this problem?
    Thanks you in advance, Clemens Eisserer

    Well, thanks for the tips!
    Since I am running Unix '\n' shoulb we enough, but thanks for remembering me g
    Well, I actually forgot to flush the output-Stream. Nobody is perfect ;-)
    Thanks again, lg Clemens

  • Java Input and Output streams

    I have maybe simple question, but I can`t really understand how to figure out this problem.
    I have 2 applications(one on mobile phone J2ME, one on computer J2SE). They commuinicate with Input and Output Streams. Everything is ok, but all communication is in sequence, for example,
    from mobile phone:
    out.writeUTF("GETIMAGE")
    getImage();
    form computer:
    reply = in.readUTF();
    if(reply.equals("GETIMAGE")) sendimage()
    But I need to include one simple thing in my applications - when phone rings there is function in MIDlet - pauseApp() and i need to send some signal to Computer when it happens. But how can i catch this signal in J2SE, because mayble phone rings when computer is sending byte array? and then suddnely it receives command "RINGING"....?
    Please explain how to correcly solve such problem?
    Thanks,
    Ervins

    Eh?
    TCP/IP is not a multiplexed protocol. And why would you need threads or polling to decipher a record-oriented input stream?
    Just send your images in packets with a type byte (1=command, 2=image, &c) and a packet length word. At the receiver:
    int type = dataInputStream.read();
    int length = dataInputStream.readInt();
    byte[] buffer = new byte[length];
    int count, read = 0;
    while ((count = dataInputStream.read(buffer,count,buffer.length)) > 0)
    read += count;
    // At this point we either have:
    // type == -1 || count = -1 => EOF
    // or count > 0, type >= 0, and buffer contains the entire packet.
    switch (type)
    case -1:
    // EOF, not shown
    break;
    case COMMAND: // assuming a manifest constant somewhere
    // process incoming command
    break;
    case IMAGE:
    // process or continue to process incoming image
    break;
    }No threads, no polling, and nuthin' up my sleeve.
    Modulo bugs.

  • Java.lang - process builder

    I want to execute the following command inside my java program
    rep_cmd [file1] -text [file2]
    The above command belongs to an application installed on my PC.
    The above command when executed in the command prompt works fine.
    but it does not work inside my java program
    here is my code:
    public class ProcBuild
    public static void main(String args[]) throws IOException, InterruptedException
    String cmdLine="cmd /c rep_cmd log.wgl -text log1.txt";
    ProcessBuilder pr=new ProcessBuilder(cmdLine);
    pr.start();
    and here is my error message with output:
    run:
    Exception in thread "main" java.io.IOException: Cannot run program "cmd /c "rep_cmd log.wgl" -text "log1.txt"": CreateProcess error=2, The system cannot find the file specified
         at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
         at ProcBuild.main(ProcBuild.java:23)
    Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
         at java.lang.ProcessImpl.create(Native Method)
         at java.lang.ProcessImpl.<init>(ProcessImpl.java:188)
         at java.lang.ProcessImpl.start(ProcessImpl.java:132)
         at java.lang.ProcessBuilder.start(ProcessBuilder.java:1021)
         ... 1 more
    Java Result: 1
    BUILD SUCCESSFUL (total time: 0 seconds)
    Edited by: user13286843 on Jan 20, 2012 9:20 AM

    >
    Exception in thread "main" java.io.IOException: Cannot run program "cmd /c "rep_cmd log.wgl" -text "log1.txt"":
    >
    You are passing the entire command as one String and the string is being interpreted as the name of the program and no arguments.
    See the Javadocs for ProcessBuilder. It has an example that shows how to pass the cmd, and each argument as separate Strings.
    Get the Javadoc example working first and then substitute your command and arguments.
    Starting a new process which uses the default working directory and environment is easy:
    Process p = new ProcessBuilder("myCommand", "myArg").start();
    Here is an example that starts a process with a modified working directory and environment:
    ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
    Map<String, String> env = pb.environment();
    env.put("VAR1", "myValue");
    env.remove("OTHERVAR");
    env.put("VAR2", env.get("VAR1") + "suffix");
    pb.directory(new File("myDir"));
    Process p = pb.start();

  • About java.lang.Process class?

    hi, i am executing one batch file (it contains 2 executable statements) through java.lang.Runtime class exec method like this..Process p1=r.exec("cmd /K start .\\Skeletons\\reports\\FormatFiles\\"+strDTab+".bat");.. i want to get the output of this process is it success, failure or suspect?. how to use the waitFor() method of Process class in this situation?. and also the execution of the batch program will give some status (if fail it will throw some exception), i want to catch the status. depending on the status i will decide proceed to further statements or not?..

    You use waitFor() by calling it on the process you get back from the exec()
    If you want examples use google to find them.

  • Java.lang.NullPointerException and ConnectionPool problem

    refresh page , problem gone
    java.lang.NullPointerException
    at Deferment.UpdatePostgraduate.getStatus(UpdatePostgraduate.java:278)
    at Deferment.UpdatePostgraduate.doPost(UpdatePostgraduate.java:175)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    at org.apache.catalina.servlets.InvokerServlet.serveRequest(InvokerServlet.java:402)
    at org.apache.catalina.servlets.InvokerServlet.doPost(InvokerServlet.java:170)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    UpdatePostgraduate.java:278
    ->while (rs.next()) {
    175-> tarCount=getStatus(userid);
    now I have
    Connection conn = null;
    CallableStatement calstat=null;
    ResultSet rs = null;
    in every of my function
    and my
    public Connection getConnection()         throws SQLException, ServletException       {           Connection conn = null;           try{           pool.getConnection();           }catch (SQLException sqle) {             throw new ServletException(sqle.getMessage());         }           return conn;       }

    private DataSource pool = null; 
        int tarCount;
        int sendMail;
        @Override
        public void init() throws ServletException {
            Context env = null;
            try {
                env = (Context) new InitialContext().lookup("java:comp/env");
                pool = (DataSource) env.lookup("jdbc/test");
                if (pool == null) {
                    throw new ServletException(
                            "'jdbc/test' is an unknown DataSource");            }
            } catch (NamingException ne) {
                throw new ServletException(ne);
          public Connection getConnection()
            throws SQLException, ServletException
              Connection conn = null;
              try{
             conn=pool.getConnection();
              }catch (SQLException sqle) {
                System.out.println("JDBC error:" + sqle.getMessage());
                sqle.printStackTrace();
              return conn;
          }then on every function I call it like
    private int getFound(String UNumber) throws Exception {
            Connection conn = null;
            CallableStatement calstat=null;
            ResultSet rs = null;
            try {
                conn = pool.getConnection();
                calstat = (CallableStatement) conn.prepareCall("{call DuplicatePost(?)}");
                calstat.setString(1, UNumber);
                rs = calstat.executeQuery();
                tarCount = 0;
                while (rs.next()) {
                    tarCount++;
            } catch (SQLException se) {
                System.out.println("JDBC error:" + se.getMessage());
                se.printStackTrace();
            } catch (Exception e) {
                System.out.println("other error:" + e.getMessage());
                e.printStackTrace();
            } finally {
                try {
                    if (rs != null) {
                        rs.close();
                    if (calstat != null) {
                        calstat.close();
                } catch (SQLException e) {
                    e.printStackTrace();
            } //end finally
            return tarCount;
        }// end function
    }// end

Maybe you are looking for

  • How can I lock the annotations on my PDF file in Adobe reader version 5 with write access

    I have Adobe Acrobat ver 5.0. I have labelled (annotated) certain fields in my files. Now I need to lock the label to make it write protected.

  • How do I revert my iPhoto to the Original File?

    I have Mac OS X - Version 10.5.8 - iPhoto 9 I have a numerious amount of photo's that look fine in thumbnail but when opened I am given a "!".  I have done the suggested Command+Option keys held down and rebuild the library.  This did not work!  But

  • Set Column width in query (not using SQL*Plus)

    How can I Set Column width in query I understand you can set column width using column col1 FORMAT A5 select col1 from table1;But this only works in SQL*Plus I want to be able to do this in a regular SQL query window (not in SQL*Plus), how can I do i

  • Can't open pdf files on link

    Hello everybody, I'm facing a strange problem. We recently moved a part of a file server on a different partition (due to lack of space). So, an entire subdirectory of the company moved, and we made a link on the former partition that points to the n

  • Can't connect to X11 windows server

    Hi all, I am having problems installing oracle in Fedora Core 1. This is where i'm stuck at and im not sure what to do. Preparing to launch Oracle Universal Installer from /tmp/OraInstall2004-11-24_09-23-44AM. Please wait ...[student@BI GCPU026 Disk1