Using Process Runtime.getRuntime().exec

http://im1.shutterfly.com/procserv/47b4d633b3127cceb46774c84ee80000001610
Here is a URL to a part of the current process I need to run. Actually there are 4 steps that preceed these but they are ran in order and must be done before these (that part is easy). Sorry it kinda chopped off the left side a little bit.
My question is, can I do this entirely using Runtime.getRuntime().exec() commands or do I need to involve multi threading. The reason I am asking is because P13 cannot run until P8 and P9 completes, but that shouldn't stop the rest of the program from running.
If I have something like
Process P4 = Runtime.getRuntime().exec(P4);
Process P5 = Runtime.getRuntime().exec(P2);
// Some handling for the streams of these processes goes here
P4.waitFor();
P2.waitFor();
if(P2.exitValue() != 0){
Process P5 = Runtime.getRuntime().exec(P5);
Process P6 = Runtime.getRuntime().exec(P6);
// Some handling for the streams of these processes goes here
Does that mean the whole program will stop and wait until P4 is done before even checking for P2? If P2 is finished would the program continue and run P5 and P6 even if P4 is still running or will it wait for P4 to complete also. P4 has nothing to do with P2?
Also any advice ???

P4 and P2 will both be running in parallel (or as much as your OS and hardware allows them to be). As soon as both are done, and regardless of which finishes first, whatever follows P2.waitFor() will execute.
If you have multiple groups of processes, where the processes within a group must execute sequentially, but the groups themselves can run independently of each other, then you'll need to either use Java's threads, or wrap each group of sequential processes in a shell script or batch file the executes that group sequentially.
If there are complex dependencies among the groups--that is, multiple groups must wait on the same process, or one group must wait for multiple other groups, then it might be easier to control the concurrency in Java.

Similar Messages

  • Unable to run certain commands on unix using the Runtime.getRuntime().exec(

    Hi Folks,
    I am unable to get any output if I try : Runtime.getRuntime().exec("who am i")
    however for Runtime.getRuntime().exec("pwd") I am getting the present working directory path !!!
    if I give Runtime.getRuntime().exec("echo $PATH") then instead of printing the path it prints $PATH instead !!! similarly it is unable to understand any of the special unix characters such as " or ' & is assuming it to be a literal instead.
    Any idea why this is happening ?? and any solution for the same
    regards
    Anand

    I don't think that Runtime.getRuntime().exec() spawns a shell it just executes the file that is specified in the string. ecause of this you can not use commands that are built-in in the shell directly nor use special shell characters. You must spawn your own shell, try something like this:
    Runtime.getRuntime().exec("sh");I'm sure you can add some switch to sh to execute a command by I am not using unix myself so I don't know how. Someone else have to help you with that. You can allways read the man-pages.

  • Opening a new browser using Runtime.getRuntime().exec(cmd); under windows

    Can Runtime.getRuntime().exec(cmd); open a URL in to a new browser in wondows OS or ...can we force it to any specific browser insted on OS's default browser...
    It does open a new bowser under MAC but not under windows..
    cmd = "'rundll32 url.dll,FileProtocolHandler"+URL (windows)
    Thanks

    public class WindowsProcess
         public static void main(String[] args)
              throws Exception
              String[] cmd = new String[3];
              cmd[0] = "cmd.exe";
              cmd[1] = "/C";
              cmd[2] = "start";
              Process process = Runtime.getRuntime().exec( cmd );
              process = Runtime.getRuntime().exec( cmd );
    }When you run the above code you should get two open dos windows.
    Now just just enter some html filename and hit enter in each window. IE should start up separately in each window.
    Thats also what should happen if you specify the html file as the fourth parameter. A new process should be created and two separate windows should open with a browser in each.

  • Strange behaviour of Runtime.getRuntime().exec(command)

    hello guys,
    i wrote a program which executes some commands in commandline (actually tried multiple stuff.)
    what did i try?
    open "cmd.exe" manually (administrator)
    type "echo %PROCESSOR_ARCHITECTURE%" and hit enter, which returns me
    "AMD64"
    type "java -version" and hit enter, which returns me:
    "java version "1.6.0_10-beta"
    Java(TM) SE Runtime Environment (build 1.6.0_10-beta-b25)
    Java HotSpot(TM) 64-Bit Server VM (build 11.0-b12, mixed mode)"
    type "reg query "HKLM\SOFTWARE\7-zip"" returns me:
    HKEY_LOCAL_MACHINE\SOFTWARE\7-zip
    Path REG_SZ C:\Program Files\7-Zip\
    i wrote two functions to execute an command
    1) simply calls exec and reads errin and stdout from the process started:
    public static String execute(String command) {
              String result = "";
              try {
                   // Execute a command
                   Process child = Runtime.getRuntime().exec(command);
                   // Read from an input stream
                   InputStream in = child.getInputStream();
                   int c;
                   while ((c = in.read()) != -1) {
                        result += ((char) c);
                   in.close();
                   in = child.getErrorStream();
                   while ((c = in.read()) != -1) {
                        result += ((char) c);
                   in.close();
              } catch (IOException e) {
              return result;
         }the second function allows me to send multiple commands to the cmd
    public static String exec(String[] commands) {
              String line;
              String result = "";
              OutputStream stdin = null;
              InputStream stderr = null;
              InputStream stdout = null;
              // launch EXE and grab stdin/stdout and stderr
              try {
                   Process process;
                   process = Runtime.getRuntime().exec("cmd.exe");
                   stdin = process.getOutputStream();
                   stderr = process.getErrorStream();
                   stdout = process.getInputStream();
                   // "write" the parms into stdin
                   for (int i = 0; i < commands.length; i++) {
                        line = commands[i] + "\n";
                        stdin.write(line.getBytes());
                        stdin.flush();
                   stdin.close();
                   // clean up if any output in stdout
                   BufferedReader brCleanUp = new BufferedReader(
                             new InputStreamReader(stdout));
                   while ((line = brCleanUp.readLine()) != null) {
                        result += line + "\n";
                   brCleanUp.close();
                   // clean up if any output in stderr
                   brCleanUp = new BufferedReader(new InputStreamReader(stderr));
                   while ((line = brCleanUp.readLine()) != null) {
                        result += "ERR: " + line + "\n";
                   brCleanUp.close();
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              return result;
         }so i try to execute the commands from above (yes, i am using \\ and \" in java)
    (1) "echo %PROCESSOR_ARCHITECTURE%"
    (2) "java -version"
    (3) "reg query "HKLM\SOFTWARE\7-zip""
    the first function returns me (note that ALL results are different from the stuff above!):
    (1) "" <-- empty ?!
    (2) java version "1.6.0_11"
    Java(TM) SE Runtime Environment (build 1.6.0_11-b03)
    Java HotSpot(TM) Client VM (build 11.0-b16, mixed mode, sharing)
    (3) ERROR: The system was unable to find the specified registry key or value.
    the second function returns me:
    (1) x86 <-- huh? i have AMD64
    (2) java version "1.6.0_11"
    Java(TM) SE Runtime Environment (build 1.6.0_11-b03)
    Java HotSpot(TM) Client VM (build 11.0-b16, mixed mode, sharing)
    (3) ERROR: The system was unable to find the specified registry key or value.
    horray! in this version the java version is correct! processor architecture is not empty but totally incorrect and the reg query is still err.
    any help is wellcome
    note: i only put stuff here, which returns me strange behaviour, most things are working correct with my functions (using the Runtime.getRuntime().exec(command); code)
    note2: "reg query "HKLM\HARDWARE\DESCRIPTION\System\CentralProcessor\0" /t REG_SZ" IS working, so why are "some" queries result in ERR, while they are working if typed by hand in cmd.exe?

    ok, i exported a jar file and execute it from cmd:
    java -jar myjar.jar
    now the output is:
    (1) "" if called by version 1, possible to retrieve by version 2 (no clue why!)
    (2) "java version "1.6.0_10-beta"
    Java(TM) SE Runtime Environment (build 1.6.0_10-beta-b25)
    Java HotSpot(TM) 64-Bit Server VM (build 11.0-b12, mixed mode)"
    (3) C:\Program Files\7-Zip\
    so all three problems are gone! (but its a hard way, as i need both functions and parse a lot of text... :/ )
    thanks for the tip, that eclipse changes variables (i really did not knew this one...)

  • PROBLEM in executing a shell command through Runtime.getRuntime().exec()

    Hi all,
    I was trying to execute the following code:
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.sql.CallableStatement;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.Statement;
    import java.sql.ResultSet;
    * Created on Mar 13, 2007
    * To change the template for this generated file go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    * @author 195092
    * To change the template for this generated type comment go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    public class ClassReportDeleteDaemon {
         ClassReportDeleteDaemon()
         public static void main(String[] args) throws Exception
              Connection conn = null;
              Statement stmt = null;
              ResultSet rs;
              String strQuery = null;
              String strdaysback = null;
              String delstring = null;
              int daysback;
              try
                   System.out.println("REPORT DELETION ::: FINDING DRIVER");               
                   Class.forName("oracle.jdbc.driver.OracleDriver");
              catch(Exception e)
                   System.out.println("REPORT DELETION ::: DRIVER EXCEPTION--" + e.getMessage());
                   System.out.println("REPORT DELETION ::: DRIVER NOT FOUND");
              try
                   String strUrl = "jdbc:Oracle:thin:" + args[0] + "/" + args[1] + "@" + args[2];
                   System.out.println("REPORT DELETION ::: TRYING FOR JDBC CONNECTION");
                   conn = DriverManager.getConnection(strUrl);
                   System.out.println("REPORT DELETION ::: SUCCESSFUL CONNECTION");
                   while(true)
                        System.out.println("WHILE LOOP");
                        stmt = conn.createStatement();
                        strQuery = "SELECT REP_DAYS_OLD FROM T_REPORT_DEL";
                        rs = stmt.executeQuery(strQuery);
                        while(rs.next())
                             strdaysback = rs.getString("REP_DAYS_OLD");
                             //daysback = Integer.parseInt(strdaysback);
                        System.out.print("NO of Days===>" + strdaysback);
                        delstring = "find /tmp/reports1 -name " + "\"" + "*" + "\"" + " -mtime +" + strdaysback + " -print|xargs rm -r";
                        System.out.println("DELETE STRING===>" + delstring);
                        Process proc = Runtime.getRuntime().exec(delstring);
                        //Get error stream to display error messages encountered during execution of command
                        InputStream errStream=proc.getErrorStream();
                        //Get error stream to display output messages encountered during execution of command
                        InputStream inStream = proc.getInputStream();
                        InputStreamReader strReader = new InputStreamReader(errStream);
                        BufferedReader br = new BufferedReader(strReader);
                        String strLine = null;
                        while((strLine=br.readLine())!=null)
                             System.out.println(strLine);
                   }     //end of while loop
              }     //end of try
              catch (Exception e)
                   System.out.println("REPORT DELETION ::: EXCEPTION---" + e.getMessage());
                   conn.close();
         }     //end of main
    }     //end of ClassReportDeleteDaemon
    But it is giving the error "BAD OPTION -print|xargs". The command run well in shell.
    Please help.
    Thanking u.......

    Since the pipe '|' is interpreted by the shell then you need the shell to invoke your command
            String[] command = {"sh","-c","find /tmp/reports1 -name " + "\"" + "*" + "\"" + " -mtime +" + strdaysback + " -print|xargs rm -r"};
            final Process process = Runtime.getRuntime().exec(command);
      You should also read http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html at least twice and implement the recommendation regarding stdout and stderr.
    P.S. Why are you not using Java to find and delete these files?
    Message was edited by:
    sabre150

  • InputStream hung from Runtime.getRuntime().exec

    Dear all,
    I am trying to use the following code to run a Runtime.getRuntime().exec("my_selection.exe") method and redirect all the output from the process to my JTextArea.
    My program is an executable called "my_selection.exe", which runs under DOS something like:
    My Selection Utilities:
    type the command -
    o : open an item
    l : list subitems
    q : exit
    Please select your options:But when I run my Test program, the above selection menu does not show in my JTextArea. Only after I type q (which is exit command in my_selection), will all the output shown in TextArea.
    I tested the inputstream.available(), but it always == 0.
    Anyone can help point me out what is wrong here?
    BTW, when I use the same program to run "copy a.txt a" by exec("cmd.exe"), it works ok, no matter whether it prompts for owerwrite the existing file or not.
    Many thanks!
    I tried the code,
    /* part of the code */
    public static void main(String[] args) {
         Test t = new Test();
         t.setTitle("Basic GUI");
         t.init(); // init GUI
         t.connect();
         t.show();
    private static void log(Object text) {
         getTextArea().setCaretPosition(getTextArea().getText().length());
         getTextArea().setText(getTextArea().getText() + text.toString() + "\n");
    private Thread getInputStreamListener() {
         if(listener == null) {
              Runnable runnable = new Runnable() {
                   public void run() {
                        try {
                             String text = "";
                             while (true) {
                                  while (inputStream.available()==0) {
                                       Thread.currentThread().sleep(100);
                                  byte[] bytes = new byte[inputStream.available()];
                                  inputStream.read(bytes);
                                  text = new String(bytes);
                                  log("> " + text);
                        catch(Exception e) {
                             handleException(e);
              listener = new Thread(runnable);
              listener.setName("out listener");
              listener.setPriority(2);
              listener.start();
         return listener;
    private Thread getErrorStreamListener() {
         if(listener == null) {
              Runnable runnable = new Runnable() {
                   public void run() {
                        try {
                             String text = "";
                             while (true) {
                                  while (errorStream.available()==0) {
                                       Thread.currentThread().sleep(100);
                                  byte[] bytes = new byte[errorStream.available()];
                                  errorStream.read(bytes);
                                  text = new String(bytes);
                                  log("> " + text);
                        catch(Exception e) {
                             handleException(e);
              listener = new Thread(runnable);
              listener.setName("out error listener");
              listener.setPriority(2);
              listener.start();
         return listener;
    private static void handleException(Throwable t) {
         log(t);
    private void connect() {
         try{
              process = Runtime.getRuntime().exec(new String[] {"my_selection.exe"});
              inputStream = new BufferedInputStream(process.getInputStream());
              outputStream = new BufferedOutputStream(process.getOutputStream());
              errorStream = new BufferedInputStream(process.getErrorStream());
              getInputStreamListener();
              getErrorStreamListener();
         catch(Exception e) {
              log(e);

    Note in the above code all "listener" variable in:
    private Thread getErrorStreamListener() method
    show be "listener1".
    Even I changed it, it does not work either.
    Please help.
    Thanks!

  • 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("/usr/bin/env") crashes on Solaris

    I am trying to write a Java class to read environment variables on Solaris. I have read a few posts on this forum and it appears that other people have had no trouble in doing this. I have written the following code to execute the unix 'env' command and read in the standard input stream from the output.
    // start
    Process process = Runtime.getRuntime().exec("/usr/bin/env");
    try {
    process.waitFor();
    if (process.exitValue() != 0) {
    return "Process exited with non-zero status";
    catch (InterruptedException intexc) {
    return "ERROR: "+intexc.getMessage();
    BufferedReader br1 = new BufferedReader(new InputStreamReader(process.getInputStream()));
    // blah, blah, blah, code to parse input from process
    // end
    The problem that I am having is that the class crashes whenever it is run. I have substituted 'env' for a number of other commands and these work ok which makes me suspect that there is some percularity with the 'env' program. Also, the code appears to halt on the 'exec' so it is nothing to do with the reading of input, it is the actual execution of the command that it causing the problem.
    Does anyone have any experience of using 'env' in this way under Solaris or has anyone managed to develop a similar class? Any help greatly appreciated.
    Cheers,
    Jon.

    Found a solution to this in the bug database.
    Bug ID: 4098442

  • Runtime.getRuntime().exec problem with linux script.

    Hello,
    I try to start a script under Linux RedHat 9. This script must just create another file.
    I work with JDK 1.4.1_02b06.
    If I use the next command
    process = Runtime.getRuntime().exec("/temp/myScript.sh");
    This is not working. I script file is existing otherwise I receive an error. I don't understand why the script is not executed!
    I have check some other posts in this forum but I cannot find the solution.
    Thanks in advance for your help.
    Alain.

    Try running it with sh: Runtime.getRuntime().exec("sh /temp/myScript.sh");

  • Runtime.getRuntime().exec launching 2 FireFox instances, when 1 expected

    Hi,
    I'm using the following piece of code to launch default browser of my system
    process = Runtime.getRuntime().exec("rundll32"   +  " " + "url.dll,FileProtocolHandler" +  " " + "www.google.com");It works absolutely fine when I've IE6/IE7 as my system default browsers. But when I set Firefox as default browser, at times this command launches 2 instances of Firefox with same url.
    I tried executing the above command from command line and I didn't face any issues with Firefox as default browser. Only when I'm calling from Java code using "exec" command, I'm facing this issue...
    Thanks in advance,
    Vinayak

    Hi Vinayak,
    It seems to be running fine on my machine. with FireFox Version 1.5.0.9 and JDK 1.5.
    Cheers
    Rahul

  • SWT window disappear while running Runtime.getRuntime().exec()

    Hello,
    I have create a SWT application. I am executing the folloiwng code from my SWT application.
    Process process = Runtime.getRuntime().exec(param);
    BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line = null;
    while ((line = in.readLine()) != null) {
    During execution of the above code when click on other icon of the window task bar and click back on SWT window Icon, The windows open but it does not show annything until the code execution finish. any help would be apprecited.

    This isn't an SWT forum. In the future, please post such questions on a forum specifically for SWT issues.
    But to answer your question, there's a 99.9% chance this is because you're launching the process on SWT's UI thread. Similar to performing long-running tasks on Swing's EDT, this is a no-no. The SWT UI won't be able to repaint itself until after your process has finished. To remedy this, launch your process in a separate Thread.

  • Runtime.getRuntime.exec() not working with through Servlet

    Hi ,
    I want to open a IE from servlet,I am using a Runtime.getRuntime.exec to open the browser ,but my servlet is executing but IE is not opening...Here i am using TomcatServer...Is any settings to be Done in TomcatServer.
    My Servlet code is
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException
         String s1 = "C:/Program Files/Internet Explorer/IEXPLORE.EXE";
         String s2 = "http://192.168.0.149:8080/etk/etk3.htm";
         Runtime runtime = Runtime.getRuntime();
         runtime.exec(s1 + " " + s2);
    i know it is contrary to the purpose servlets are meant for.but i am using for different purpose..
    help me on this one...
    Thanks in Advance

    No, I am using the right path, I am sure. Also I tried giving the absolute path of the UserGuide.pdf. Still it cannot find. Please anyone try spawning an application from a different directory and lemme know your openion.
    Regards,
    Thomas.

  • Runtime.getRuntime().exec - relies on the J2RE?

    Well here is a problem...
    My program works fine using the Runtime.getRuntime().exec command, and the program works as-intended on my computer. But that's because I have the latest and greatest Java apparel (especially the J2RE).
    Now, a friend of mine who does not program, took my program and tried it on his computer. It worked (the GUI loaded and buttons functioned) but it didn't actually do anything other than serve as a nice-looking GUI lol.
    The problem was, it was creating the file I had it create (using FileWriter) but it wasn't EXECUTING that file like I designed the program to.
    I used the Runtime.getRuntime().exec to execute the file - my question is, if the person doesn't have the Java Runtime Environment, will that command work? He clearly has Java on his computer (the GUI loaded) but he might not have the J2RE...
    Any thoughts? Any suggestions for an alternative way to execute a file?
    Thanks!
    -Josh

    I don't understand why this wont work on other
    people's computers...
    I create the file "commands.bat" in their C:\
    directory. I then have the following command to
    execute it:
    Runtime.getRuntime().exec("cmd.exe /c
    \"C:\\crasher.bat\"");It works perfect for me... But it doesn't work for
    other people. For other people, it creates the batch
    file in the right place, it just wont execute it and
    I am not sure why...
    -JoshYou said "commands.bat" but your code is executing "crasher.bat". I have the feeling you're trying to crash their computers or something?
    cmd.exe is an executable on certain flavors of Windows. Other flavors of Windows have command.exe, not cmd.exe. So you have to pick the same platform, or make the actual command that you execute be dynamic (read it from a property file to determine what to execute).
    Go to those other machines and see if you can execute that same command from the command line. Do some debugging for pete's sake.

  • Runtime.getRuntime().exec(java test)

    Hi,
    As part of a thesis for college, I am trying to execute a test java program. The program executes okay and I can read the results okay.
    Sample code.
    process = Runtime.getRuntime().exec("java test");
    InputStream iOutStream = process.getInputStream();
    InputStream ErrorStream = process.getErrorStream();
    However, I need to be able to execute a progam that reads a parameter from the screen. I tried to pass a parameter file but it doesn't work.
    process = Runtime.getRuntime().exec("java test <input.txt");
    I also tried just passing the parameters as a string array but it doesn't work either.
    process = Runtime.getRuntime().exec("java test 2, 2");
    Is there any other way that I can get the process to accept parameters?
    My deadline is looming so any help would be greatly appreciated.
    Thanks
    Eleanor
    [email protected]

    I think you are waiting when reading the output before you write to the stream until it becomes NULL or -1. That will never finish if the program you execute is expecting input!
    See a working example:
    This class does nothing than print a line on the console, then waits for a line of input, then prints the result again on the console. This is the class you'd execute from some other java code:
    import java.io.*;
    public class Input {
        public static void main(String args[]) {
            try {
                System.out.println("Before input");
                BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
                String s=r.readLine();
                System.out.println("Got line : " + s);
            } catch(Exception e) {
                    System.out.println(e.getMessage());
    }The following 'controls' the input-test class above, so compile the classes and execute the following one:
    import java.io.*;
    import java.lang.*;
    public class test {
        public static void main(String args[]) {
            try {
                Process p = Runtime.getRuntime().exec("java Input");
                BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
                BufferedWriter w = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
                String s=r.readLine(); // You cannot read until NULL because that will not happen before you have 'input' something
                System.out.println("Got: " + s);
                w.write("cvxcvxcvx\n\r");
                w.flush();
                System.out.println("waiting result:");
                while( (s=r.readLine()) != null) { // read until finished.
                    System.out.println("after : " + s);
            } catch(Exception e) {
                    System.out.println(e.getMessage());               
    }

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

Maybe you are looking for