Using BufferedReader

Hello, I have an app which has a class which I pass the System.in to and basically passes it to a BufferedReader:
// System.in is automatically opened when your program starts.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while ((line = br.readLine()) != null) {
// do something with variable "line" here
br.close();
I call this class whenever I need the next line - which I do some formatting to and return the results.
The only issue I noticed is a good portion of my execution time is spent pulling up the next line coming in - and since very large amount of text may be getting piped over to the app, I'm guessing that may be the issue. I see you can adjust the Buffer Size, I'm wondering if that would increase the speed.
Any suggestions as to what values I should set int sz to?

But even if that isn't the issue, if I know it will
be getting text files of large sizes, should I
increase the Buffer size? The app will be running on
a large server.That buffer size will probably not affect the speed of your application since it doesn't change the buffer size for stdin for the process. The buffer associated with stdin is created and held by the OS. An application can't write 1MB to that buffer since the buffer usually is very small, the process which writes to stdin will be blocked/halted when the buffer is full (if you aren't reading it fast enough)
Kaj

Similar Messages

  • Throws IllegalArgumentException when use BufferedReader.readLine()

    hi
    when i use BufferedReader.readLine() to read a html file of Internet,it throws IllegalArgumentException like blow:
    java.lang.IllegalArgumentException
    at java.nio.Buffer.position(Buffer.java:218)
    at java.nio.charset.CharsetDecoder.decode(CharsetDecoder.java:575)
    at sun.nio.cs.StreamDecoder$CharsetSD.implRead(StreamDecoder.java:442)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:182)
    at java.io.InputStreamReader.read(InputStreamReader.java:167)
    at java.io.BufferedReader.fill(BufferedReader.java:136)
    at java.io.BufferedReader.readLine(BufferedReader.java:299)
    at java.io.BufferedReader.readLine(BufferedReader.java:362)
    but it occured sometimes or occured never in a long time!
    Why?

    It does it because of this bit of code in java.nio.Buffer.position
    if ((newPosition < 0) || (newPosition > limit))
          throw new IllegalArgumentException ();So for some reason a bit of the java code has tried to set the position to either less than zero or greater than the limit of the buffer. Not a good idea in either case.
    Since this is not your code you can't really do much about it. Try catching the exception and handling it.

  • Keyboard input using BufferedReader

    Trying to use BufferedReader for keyboard input, first of all is it possible? And second how do I do construct the stream?
    I am trying BufferedRead in = new BufferedReader(System.in); and this is not working .
    Please help.

    Trying to use BufferedReader for keyboard input, first
    of all is it possible? And second how do I do
    construct the stream?
    I am trying BufferedRead in = new
    BufferedReader(System.in); and this is not working .
    Please help.Try this. I got it from Core Java 1.2 Volume 1 - Fundamentals by Horstmann and Cornell:
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));To read something from the console at that point you'd do something like this:
    String inputData=in.readLine();Hope that helps.

  • Diff bet  args and using BufferedReader(new InputStreamReader(System.in))

    What is the differece between getting a string via args and using BufferedReader(new InputStreamReader(System.in))??????
    Please help me to know

    via argsI presume you mean the command line arguments? Well that'd be the command line arguments: ergo: "Hello World" would be the arguments in: java -cp . Say "Hello World"
    System.in is the standard input stream... The console (ie the keyboard) when a java program is run within a "standard" command line environment.
    Cheers. Keith.

  • Using BufferedReader to get Unicode data from a .php site

    Hi,
    Probably a rather mundane question. I'm working on an applet which uses a .php site as a proxy to get at data found in a mySQL database. It's working adequately for text consisting of standard English characters only - the only problem is that every time I read in a file, it starts with the characters ""
    It's not working at all for text using other characters - I get an incomprehensible string of characters in Java when I try that.
    So my assumption is that Java does not understand that my php document is in Unicode, and is trying to read it using a different encoding system. I use unicode charaters elsewhere in this applet and have no problems with them, so I am assumign it must be an I/O error.
    What do I have to do to make Java realize that this is unicode?
    Here's the relevant code as it is now:
    String goTo = "http://[...]/info.php?search=" + toLink(search);
    URL test = new URL(goTo);
    URLConnection testConnection = test.openConnection();
    BufferedReader dis = new BufferedReader(new InputStreamReader(testConnection.getInputStream()));
    String inputLine;
    while ((inputLine = dis.readLine()) != null) {
                    giveout += inputLine;
    dis.close();The String giveout should have all the data from the document in it after this.
    Or do I need to change something about my php, which, as it is now, just displays the data from my database, with no HTML tags whatsoever?

    You probably have a 'byte order marker' ( BOM ) at the beginning of the file. You can use my BOMStripperInputStream posted in reply #7 of http://forums.sun.com/thread.jspa?threadID=5310966 or you can just discard the BOM bytes from the InputStream before wrapping it in the BufferedReader.
    Hi Sabre im facin the same probem.
    bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream("C:/Documents and Settings/Administrator/Desktop/UTF8RDFiles/Example.txt"),"UTF-8"));
    bufferedReader.readLine() returns a junk character ? at the beginning of the line.
    you have instructed to use your BOMStripperInputStream posted in reply #7 of http://forums.sun.com/thread.jspa?threadID=5310966 but i dotn know how to use it with bufferedReader because i want my method to return only a BufferedReader object.
    can you suggest me how to go about it.
    my code is as below need help.
    public BufferedReader check(){
                     bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream("C:/Documents and Settings/Administrator/Desktop/UTF8RDFiles/Example.txt"),"UTF-8"));
            return bufferedReader; // need to return bufferedReader object only...since some other code needs bufferedReader ...suggest me.
    i will be highly obliged if you paste the refined code.. please need your urgent help on this...
    Regards
    Deepak

  • How to only read the last line in the text file by using BufferedReader ?

    Dear all,
    Hello, I am new to Java. Do anybody know how to read the last line (this is the last record) in the text file.The method I am now using is reading from the first line until I reach the last line in the text file. Thank you!!
    BufferedReader br = new BufferedReader(new FileReader("c:\\sdk1.4.1\\bin\\dbExport.txt"));
    DataInputStream in = new DataInputStream(new FileInputStream("c:\\sdk1.4.1\\bin\\dbExport.txt"));
    String input;
    String firstinput;
    String secondinput;
    int count=90;
    int year=1955;
    while ((input = br.readLine()) != null) {
    firstinput = input.substring(0, 10);
    secondinput = input.substring(10);
    String insertStore1 = ("INSERT INTO AUTHORS " +
    "VALUES ('" + count + "', '" + firstinput + "', '" + secondinput + "', 1955)");
    System.out.println(insertStore1);
    int result = stmt.executeUpdate(insertStore1);

    I suppose you could use a java.io.RandomAccessFile.

  • Pb using BufferedReader Linux OK, Windows nOK

    Hi,
    I am using a BufferedReader to get lines of a bilingual dictionary. The dictionary is 728 000 lines that take roughly 30MB that is to say roughly 40 bytes per line.
    The program (see sample hereafter) swallows 276 818 lines (exactly) with no problem.
    Under Linux it swallows the 728 000 lines with no problem.
    I put break a point with a trap statement in order to stop the program at the very troublesome point. Then I executed step by step.
    Then just on doing a i.readLine() ( where i is the reader) the program goes directly in the finally clause where i.close() is executed,goes to the end braces of the following catch clause, then comes back to the return statement inside this clause after that the program is crashed (no return in the calling routine)
    Doesn't even execute these ex.printStackTrace(System.err); (doesn't stop at breakpoints placed here)
    At first, the while loop was
    while (str=i.readLine()!=null) {
    }I replaced it with
    Object obj=i.readLine();
    while (obj!=null) {
    str=(String) obj;
    obj=i.readLine();
    but it seems useless as the problem occurs on the read itself.
       void ExpandDictionary(String dicFileName, String signature) {
          BufferedReader i = null;
          try {
             i = new BufferedReader(new InputStreamReader(new FileInputStream(dicFileName),"UTF-8"));
             String str1 = null;
             Object obj=i.readLine();
             while (obj != null) {
                 str1=(String) obj;
                temp = new DicEntry(str1);// the DicEntry constructor splits the string into different parts
                if (temp != null) {
                   temp.entrySignature = signature;
                   entryList.add(temp);//the dictionary entry is added to the ArrayList
                } else {
                   WarningHandler.displayMessage("temp null" + str1);
                try{
                      obj=i.readLine();
                    } catch(Exception ex){
                                  ex.printStackTrace(System.err);
                                  String s=ex.getLocalizedMessage();
          } catch (Exception ex) {
                  ex.printStackTrace(System.err);
                  Logger.getLogger(Dictionary.class.getName()).log(Level.SEVERE, null, ex);
             } finally {
                         try {
                                  i.close();
                              } catch (Exception ex) {
                                          ex.printStackTrace(System.err);
                                          String s=ex.getLocalizedMessage();
                                           return;
       }I need some help.

    >
    Are you saying that you ran the code I posted*, and that it didn't process the entire file, and that it didn't throw any exception?
    If that is the case then your input file isn't what you think it is, it has some kind of problem that's (somehow?) causing a null to be prematurely passed to the i.readLine statement.Thank you for your reply.
    In fact the code inside the read loop
    create an object DicEntry that has three members each members receiving a part of the read line.
    It seems not to create problem as the program always return from its constructors with a valid value.
    But what is interesting is the following:
    If instead of creating DicEntries and adding them to the ArrayList I just add directly the String read I go further in the file
    For example instead of 220 000 lines read (roughly) I read 400 000 lines.
    If I do that one line in two (modulo 2) I read all the file.
    But I am sure, when it fails reading all the file, that it doesn't get out of the loop with a null. In this case the program would execute the statements following the loop and it is not the case (see last code and output below)
    I was suggested by an other person to do this;
    you can adjust the size of the  heap and of the stack launching  java -Xms256m -Xmx512m  nameJar.jar
    -Xms<size>        set initial Java heap size
    -Xmx<size>        set maximum Java heap size
    As I am a newbie I have to study this because I don't see clearly if it is a manual command to execute once or if I can do this by program.
    As the program is an addon of OO I don't launch it myself.
    As I did changes here is the last code I tested
    void ExpandDictionary(String dicFileName, String signature) {
            BufferedReader i = null;
            try {
                i = new BufferedReader(new InputStreamReader(new FileInputStream(dicFileName), "UTF-8"));
                String str1 = null;
                int indexL = 0;
                while ((str1 = i.readLine()) != null) {//start of the loop
                    indexL++;//count lines
                    System.out.println("IndexL=: " + Integer.toString(indexL));
                    temp = new DicEntry(str1);// DicEntry is a class with three members receiving each a part of the str1 String
                    if (temp != null) {
                        temp.entrySignature = signature;
                        entryList.add(temp);
                    } else {
                        WarningHandler.displayMessage("temp null" + str1);// a message box to the user(never entered)
                }/*end of the while loop*/
                  System.out.println("I get out of the loop ");//never pass here
            } catch (Exception ex) {
                ex.printStackTrace(System.err);
                Logger.getLogger(Dictionary.class.getName()).log(Level.SEVERE, null, ex);
                WarningHandler.displayMessage("There was a problem opening or reading the " + dicFileName +
                        " dictionary file. Please check that your file and filepath are correct and" +
                        "that your dictionary file is EUC-JP encoded");
            } finally {
                try {
                    System.out.println("I am in the finally clause");//passes here 1
                    i.close();//passes here 2
                    System.out.println("I have closed the reader");//passes here 3
                } catch (Exception ex) {
                    System.out.println("I got an exception at closure");//never passes here
                    ex.printStackTrace(System.err);
                    String s = ex.getLocalizedMessage();
                    return;//passes here 5
                //  Logger.getLogger(Dictionary.class.getName()).log(Level.SEVERE, null, ex);
                }//passes here 4
        }Here are the last lines of the output
    IndexL=: 263244
    IndexL=: 263245
    IndexL=: 263246
    IndexL=: 263247
    IndexL=: 263248
    IndexL=: 263249
    IndexL=: 263250
    IndexL=: 263251
    IndexL=: 263252
    IndexL=: 263253
    I am in the finally clause
    I have closed the reader
    I can deduce that the program doesn't exit the loop normally (no output message "I get out of the loop "), exit the try clause without entering the catch clause , goes directly to the finally clause (1) .
    Step by step I see that it executes i.close() (2) System.out.println("I have close the reader") (3); then goes on the final "brace" (4) of the catch in finally and comes back to execute return (5) but never return ('programm hanging or crashed ?)
    Here is the DicEntry code for information but it works so don't waste your time with it. Even without it the problem exists.
    class DicEntry {
       String entrySignature = "";
       String entryWriting = "";//to search the dictionary by writing
       String entryReading = "";
       String entryMeaning = "";
       DicEntry() {
        * @param str a String representing a full text line in the format of the edict dictionary file which has been decoded from EUC-JP
        * @return return a DicEntry
        * @exception exceptions No exceptions thrown
       DicEntry(String str) {
          // line sample: &#26360;&#39006;&#36865;&#26908; [&#12375;&#12423;&#12427;&#12356;&#12381;&#12358;&#12369;&#12435;] /(n) sending documents to a prosecutor/ 
          String buffer = str;
          try {
             int i = buffer.indexOf('[');
             if (i == -1) //no reading i.e. reading = writing
                i = buffer.indexOf('/');
                if (i >= 1) {
                   entryWriting = buffer.substring(0, i - 1);//remove the blank before '/'
                } else {
                 //  WarningHandler.displayMessage("no reading no / " + str);
                entryReading = entryWriting;
                if (i + 1 < str.length() && i!=-1) {
                   entryMeaning = buffer.substring(i + 1);
                } else {
                //   WarningHandler.displayMessage("no reading i+1>str.length" + str);
             } else {
                if (i >= 1) {
                   entryWriting = buffer.substring(0, i - 1);//remove the blank before '['
                } else {
               //    WarningHandler.displayMessage("else ther is writing: pb with entryWriting = buffer.substring(0, i - 1); " + str);
                if (i + 1 < str.length() ) {
                   buffer = buffer.substring(i + 1);
                } else {
               //    WarningHandler.displayMessage("else ther is writing: pb   buffer = buffer.substring(i + 1); " + str);
                i = buffer.indexOf('/');
                if (i >= 2) {
                   entryReading = buffer.substring(0, i - 2);
                } else {
               //    WarningHandler.displayMessage("else ther is writing: pb    entryReading = buffer.substring(0, i - 2); " + str);
                if (i + 1 < str.length() && i!=-1) {
                   entryMeaning = buffer.substring(i + 1);
                } else {
              //     WarningHandler.displayMessage("else ther is writing: pb  entryMeaning = buffer.substring(i + 1); " + str);
          } catch (Exception ex) {
             WarningHandler.displayMessage("There was an exception in DicEntry" + str);
             ex.printStackTrace(System.err);
             entrySignature = "";
             entryWriting = "";//to search the dictionary by writing
             entryReading = "";
             entryMeaning = "";
             return;
       }

  • Using bufferedreader to insert into a vector

    I am trying to read from a text file in an incremental fashion back into a form. I have tried it only reading the first record off the textfile and it works great; however, I run into problems when I try to read the entire file into a Vector or Array. Code is as follows:
    Vector vLine = new vLine(10,1);
    String tCardFile = new String("timecard.txt");
    File file = new File(tCardFile);
    BufferedReader br = new BufferedReader(new FileReader(file));
    String lineRead = null;
    lineRead = new String();
    while((lineRead = br.readLine()) !=null){ vLine.addElement(lineRead);}When I compile, I get this funky error that reads:
    Note: D:\javafiles\TimeCard.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.Now, I have taken the vector back out and tried using an array with 100 elements and I no longer get the above error but I run into two issues:
    First...the "timecard.txt" fill is meant to keep growing so I need a dynamic array like the vector class
    Second...I get a null value as being entered in either the array or the vector.
    Any thoughts ?

    you going to get the same compiler warning about "unchecked or unsafe operations"...
    the reason is because the compiler is not able to guarantee the type safety of your raw ( non-generified ) vector/arraylist operations...
    i.e.
    Vector v = new Vector(); // raw vector
    String s = "a string";
    Integer i = new Integer(1);
    v.add(s); // able to add arbitrary types like a String
    v.add(i); // or an Integer
    String k = (String) v.element(1); // class cast exceptionto fix this, you use generics... then the compiler will ensure that only the data type that the vector is declared to accept via generics will be allowed
    Vector<String> v = new Vector<String>(); // raw vector
    String s = "a string";
    Integer i = new Integer(1);
    v.add(s); // works because v is a Vector of Strings
    v.add(i); // will not work because a Vector of String cannot accept Integer objects
    String k = v.element(1); // no cast necessary because the Vector on handles Stringsit's the same with an ArrayList...
    ArrayList<String> al = new ArrayList<String>();
    have fun...
    - MaxxDmg...
    - ' He who never sleeps... '                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Problems in Read a file using BufferedReader

    i wrot the follwing code to search for a word in a list of files
    when i compile it ,it does not give me any error , but at run it give me the following Eception:
    java.io.FileNotFoundException: home.html (The system cannot find the file specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.(Unknown Source)
    at java.io.FileReader.(Unknown Source)
    at webSearchServlet.readFile(webSearchServlet.java:111)
    at webSearchServlet.doGet(webSearchServlet.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at desisoft.server.servlets.Servlet.service(Servlet.java:86)
    at desisoft.server.servlets.Servlet.doService(Servlet.java:62)
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import java.lang.String.*;
    public class webSearchServlet extends HttpServlet{
         String[] path;
         PrintWriter out;
         String search ;
         int num = 0;
    public void doGet(HttpServletRequest req,
    HttpServletResponse res)
    throws ServletException, IOException{
    try {
    Statement stmt;//used for database access
    ResultSet rs;//used for database access
    Connection conn;
    //Set the content type of the data to be sent back
    // to the client.
    res.setContentType("text/html");
    //Get an output writer object to send data back to
    // the client.
    out= res.getWriter();
    //Begin constructing the HTML page to send back to
    // the client.
    out.println("<HTML>");
    out.println("<HEAD><TITLE>Search </TITLE></HEAD>");
    out.println("<BODY>");
    //Register the JDBC driver
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    //Construct URL for database on node3
    String url = "jdbc:odbc:search";
    String username="";
    String password="";
    //Get a connection to the database
    conn = DriverManager.getConnection(url,username,password);
    //Get a Statement object
    stmt = conn.createStatement();
    search = req.getParameter("search");
    //Create a statement object linked to the database
    // connection.
    stmt = conn.createStatement();
    //Use the statement object to execute a query on the
    // database.
    String query = "SELECT Path FROM searchTable";
    rs = stmt.executeQuery(query);
    ResultSetMetaData resultSetMetaData =
    rs.getMetaData();
    int numColumns = resultSetMetaData.getColumnCount();
    path = new String[numColumns];
         while (rs.next()) {
              path[num] = rs.getString("Path");
              num++;
         String[] result = searchString(search ,num);
    conn.close();
    catch(Exception e){e.printStackTrace();}
    for (int i=0 ; i<path.length ;i++){
         String output = readFile(path[i] ,search);
         if(output == "yes"){
              out.println("<h2>The word you search for <i>"+search
              +"</i> was found in the file <i>"+path[i]+"</i></h2><br>");
         else
         out.println("<h2>The word you search for <i>"+search
         +"</i> was <b>NOT<b> found in the file <i>"+path[i]+"</i></h2><br>");
    /* a method to test the quary string of the user
    *it tack a String value and return a String array.
    public String[] searchString(String str , int numberOfFiles) {
         String[] strArray =new String[numberOfFiles];
         int indexOfPlus = str.indexOf('+');
         if (indexOfPlus == -1) {
              strArray[0] = str;
              return strArray;
         else {
              String firstWord = str.substring(0 ,indexOfPlus-1);
              String secondWord = str.substring(indexOfPlus-1);
              strArray[0] = firstWord;
              strArray[1] = secondWord;
              return strArray;
    public String searchFile(String stringLine ,String word){
         int index = stringLine.indexOf(word);
         if (index == -1) return "no";
         else
         return "yes";
    public String readFile (String fileName ,String word) throws IOException ,RuntimeException ,NullPointerException
    ,FileNotFoundException {
         //Read input by lines
         FileReader fr = new FileReader(fileName);
         BufferedReader in = new BufferedReader (fr);
         String s1,s2 = new String();
         while ((s1 = in.readLine()) != null ) {
              s2 = searchFile(s1,word);
              if (s2 == "yes") break;
              else
              s2="no";
              fr.close();
              in.close();
         if (s2 == "yes") return "yes";
         else
         return "no";
    what is the wrong???
    shimaa

    You already have posted the answer:
    java.io.FileNotFoundException: home.html (The system cannot find the file specified)If you are only using "filename" for creating BufferedReader the file will be expected in the working directory of runnig application.
    Your application is the server, 'cause servlet uses servers context.
    But this will hardly be the directory for your *.html. So you have to add the path of the directory where your files are placed. (Absolute or relative to current working directory.) "path/filename"
    I don't know anything about your directory structure, you will have to find out by yourself.

  • Swing hangs when using BufferedReader

    Swing hangs when I use a buffered reader. I must be doing something wrong but don't understand what it is. If I comment out the JFrame at the begining of the following code, the input part works but the Threads window won't display. If I add the JFrame then the window displays but hangs until I type something into the input. I have tried using invokeLater on the second thread with no success. What is going on?
    import boeing.agps.formatting.UtSys;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.SwingUtilities;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Document;
    import javax.swing.text.SimpleAttributeSet;
    import javax.swing.text.StyleConstants;
    * To change the template for this generated type comment go to
    * Window>Preferences>Java>Code Generation>Code and Comments>Types
    * @author slr6053
    * @version $Id: $
    public class Test {
       static BufferedReader bufferedReadderIn = new BufferedReader(
                                                 new InputStreamReader( System.in ) );
       public static void main( String[] args ) {
          new JFrame();
          Thread t = new Thread( new Runnable() {
             public void run() {
                System.out.println( "Before while" );
                while ( true ) {
                   String input;
                   try {
                      System.out.println( "Before input" );
                      input = bufferedReadderIn.readLine();
                      System.out.println( "After input " + input );
                   } catch ( IOException e ) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                   } // read extension
          t.start();
          ThreadsWindow threadsWindow = new ThreadsWindow( "Test Thread" );
          threadsWindow.setVisible( true );
          Thread x = new Thread( threadsWindow, "Threads Window") ;
          x.start();
    * Create a stand-along window that displays the current hierarchy of
    * Thread-Groups and Threads, updating the information every second.
    * A typical output looks like:
    * Note: Thread "AGPS Main" will die and become "Thread-0" at the end of main().
    * <pre>
    * THREAD INFORMATION: 20-SEP-2002 17:49:28.0181
    * ThreadGroup "system": Max Priority = 10
    *  +-> "Signal dispatcher" Priority=5 Daemon=true
    *  +-> "Reference Handler" Priority=10 Daemon=true
    *  +-> "Finalizer" Priority=8 Daemon=true
    *  +ThreadGroup "main": Max Priority = 10
    *  +-+-> "AWT-EventQueue-0" Priority=6 Daemon=false
    *  +-+-> "SunToolkit.PostEventQueue-0" Priority=6 Daemon=false
    *  +-+-> "AWT-Motif" Priority=6 Daemon=false
    *  +-+-> "Screen Updater" Priority=5 Daemon=false
    *  +-+-> "TimerQueue" Priority=5 Daemon=true
    *  +-+-> "Thread-0" Priority=5 Daemon=false
    *  +-+-> "Help Thread" Priority=4 Daemon=false
    *  +-+-> "AGPS Execution" Priority=5 Daemon=false
    *  +-+-> "SEE Threads" Priority=5 Daemon=false
    *  +-+-> "Basic L&F File Loading Thread" Priority=4 Daemon=false
    *  +-+-> "Basic L&F File Loading Thread" Priority=4 Daemon=false
    *  +-+-> "Basic L&F File Loading Thread" Priority=4 Daemon=false
    * </pre>
    * @version $Id: ThreadsWindow.java,v 1.6 2007/08/22 14:39:02 slr6053 Exp $
    class ThreadsWindow extends JFrame implements Runnable, ActionListener {
       private JTextPane textArea ;
       private JButton startStop, closeBtn ;
       private boolean updateInformation = true ;
       private boolean exitThread = false ;
       private Document doc;
       private SimpleAttributeSet att;
       private SimpleAttributeSet attRed;
       private SimpleAttributeSet attBold;
       private SimpleAttributeSet attBold1;
        * Create and show a window that will display the Threads used in the
        * current JVM. The display will be updated every second from a newly
        * created Thread "SEE Threads".
        * @param title The window title for the window.
       public ThreadsWindow( String title ) {
          super( title ) ;
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          textArea = new JTextPane() ;
          att    = new SimpleAttributeSet();
          attBold1 = new SimpleAttributeSet( att );
          StyleConstants.setBold( attBold1, true );
          StyleConstants.setFontSize( attBold1, 14 );
          attBold = new SimpleAttributeSet( att );
          StyleConstants.setBold( attBold, true );
          attRed = new SimpleAttributeSet();
          StyleConstants.setForeground( attRed, Color.red);
          StyleConstants.setBold( attRed, true );
          doc = textArea.getStyledDocument();
          getContentPane().setLayout( new BorderLayout() ) ;
          getContentPane().add( new JScrollPane().add(
                 new JPanel().add( textArea ) ), BorderLayout.CENTER ) ;
          startStop = new JButton( "Start/Stop" ) ;
          closeBtn = new JButton( "CLOSE" ) ;
          JPanel buttons = new JPanel() ;
          buttons.setLayout( new GridLayout( 0, 2 ) ) ;
          buttons.add( startStop ) ;
          buttons.add( closeBtn ) ;
          startStop.addActionListener( this ) ;
          closeBtn.addActionListener( this ) ;
          getContentPane().add( buttons, BorderLayout.NORTH ) ;
          setSize( 300, 400 ) ;
       } // end of constructor()
        * Handle the buttons.
       public void actionPerformed( ActionEvent e ) {
          Object srcIn = e.getSource() ;
          if( srcIn instanceof JButton ) {
             JButton src = (JButton)srcIn ;
             if( src == startStop ) {
                updateInformation = !updateInformation ;
             } else if( src == closeBtn ) {
                updateInformation = false ;
                exitThread = true ;
                setVisible( true ) ;
                dispose() ;
             } // end else if
          } // end if
       } // end of actionPerformed()
        * While true, sleep 1 second and then repaint.
       public void run() {
          if ( SwingUtilities.isEventDispatchThread() ) new Exception().printStackTrace();
          setVisible( true );
          while( !exitThread ) {            // do forever
             try {
                Thread.sleep( 1000 ) ;  // update every second
             }catch( Exception sEx ) {
             if( updateInformation )
                repaint() ;
          } // end while
       } // end of run()
        * Display the hierarchy of Thread-Groups and Threads.
       public void paint( Graphics g ) {
          super.paint( g ) ;
          if( updateInformation ) {
             try {
                doc.remove(  0, doc.getLength() );
                doc.insertString( 0, "THREAD INFORMATION: " +
                               UtSys.datTimSec() + "\n", attBold1 ) ;
             } catch ( BadLocationException e1 ) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
             ThreadGroup rootT = Thread.currentThread().getThreadGroup();
             while( rootT.getParent() != null ) {
                rootT = rootT.getParent();
             }// end while
             try {
                buildThreadOutput( rootT, "" ) ;
             } catch ( BadLocationException e ) {
                // TODO Auto-generated catch block
                e.printStackTrace();
          } // end if
       } // end of paint()
        * Append to the textArea variable the passed ThreadGroup and any
        * Threads it contains. If it contains ant ThreadGroups, invoke this
        * method recursively on each of these threadGroups, etc...
        * @param tg The ThreadGroup to display
        * @param indent The indent-level String to preface each line with.
        *        This method appends "-+" to this String and passes it to the
        *        next recursive invocation.
        * @throws BadLocationException
       private void buildThreadOutput( ThreadGroup tg, String indent ) throws BadLocationException {
          doc.insertString( doc.getLength(),  "   ThreadGroup " +
                           "\"" + tg.getName() + "\":" +
                           " Max Priority = " + tg.getMaxPriority() +
                            "\n", attBold );
          indent = "      ";
          Thread threadArray[] = new Thread[ tg.activeCount() ];
          int threadCount = tg.enumerate( threadArray, false );
          for( int i = 0; i < threadCount; i++ ) {   // THREADS
             Thread thread = threadArray;
    doc.insertString( doc.getLength(), indent + thread.getId()+" "+
    " \"" +thread.getName() +
    "\" Priority=" + thread.getPriority() +
    " Daemon=" + thread.isDaemon() +
    " Active= "+ thread.isAlive() +
    " Interuppted= "+ thread.isInterrupted() +
    "\n", att ) ;
    } // end for
    ThreadGroup threadGroupArray[] = new ThreadGroup[
    tg.activeGroupCount() ];
    int threadGroupCount = tg.enumerate( threadGroupArray, false );
    for( int i = 0; i < threadGroupCount; i++ ) { // THREADGROUPS
    buildThreadOutput( threadGroupArray[i], indent ) ;
    } // end for
    } // end of buildThreadOutput
    } // end of ThreadsWindow class

    OK, this code is closer to my application. If I have the JFrame code in, it works but hangs - that is you can type in "doit" in the command line and the window comes up, and you need to type something else in the command window in order for the ThreadWindow to start updating. If you try to move the ThreadWindow it hangs.
    If you comment out the begining JFrame, the ThreadsWindow never starts. What is that I'm not understanding. The BufferedReader is not in the Main thread, it is in its own thread.
    import boeing.agps.formatting.UtSys;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Document;
    import javax.swing.text.SimpleAttributeSet;
    import javax.swing.text.StyleConstants;
    * To change the template for this generated type comment go to
    * Window>Preferences>Java>Code Generation>Code and Comments>Types
    * @author slr6053
    * @version $Id: $
    public class Test {
       static BufferedReader bufferedReadderIn = new BufferedReader(
                                                 new InputStreamReader( System.in ) );
       protected static boolean condition = false;
       public static void main( String[] args ) {
          new JFrame();
          Thread t = new Thread( new Runnable() {
             public void run() {
                System.out.println( "Before while" );
                while ( true ) {
                   String input;
                   try {
                      System.out.println( "Before input" );
                      input = bufferedReadderIn.readLine();
                      System.out.println( "After input " + input );
                      if ( input.equals( "doit" )) {
                         System.out.println("DOIT");
                         condition  = true;
                   } catch ( IOException e ) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                   } // read extension
          System.out.println("First thread started");
          t.start();
          ThreadsWindow threadsWindow = new ThreadsWindow( "Test Thread" );
          Thread x = new Thread( threadsWindow, "Threads Window") ;
          System.out.println("Second thread started");
          x.start();
        * @return Returns condition.
       public static boolean isCondition() {
          return condition;
    * Create a stand-along window that displays the current hierarchy of
    * Thread-Groups and Threads, updating the information every second.
    * A typical output looks like:
    * Note: Thread "AGPS Main" will die and become "Thread-0" at the end of main().
    * <pre>
    * THREAD INFORMATION: 20-SEP-2002 17:49:28.0181
    * ThreadGroup "system": Max Priority = 10
    *  +-> "Signal dispatcher" Priority=5 Daemon=true
    *  +-> "Reference Handler" Priority=10 Daemon=true
    *  +-> "Finalizer" Priority=8 Daemon=true
    *  +ThreadGroup "main": Max Priority = 10
    *  +-+-> "AWT-EventQueue-0" Priority=6 Daemon=false
    *  +-+-> "SunToolkit.PostEventQueue-0" Priority=6 Daemon=false
    *  +-+-> "AWT-Motif" Priority=6 Daemon=false
    *  +-+-> "Screen Updater" Priority=5 Daemon=false
    *  +-+-> "TimerQueue" Priority=5 Daemon=true
    *  +-+-> "Thread-0" Priority=5 Daemon=false
    *  +-+-> "Help Thread" Priority=4 Daemon=false
    *  +-+-> "AGPS Execution" Priority=5 Daemon=false
    *  +-+-> "SEE Threads" Priority=5 Daemon=false
    *  +-+-> "Basic L&F File Loading Thread" Priority=4 Daemon=false
    *  +-+-> "Basic L&F File Loading Thread" Priority=4 Daemon=false
    *  +-+-> "Basic L&F File Loading Thread" Priority=4 Daemon=false
    * </pre>
    * @author Tom Dickens
    * @version $Id: ThreadsWindow.java,v 1.6 2007/08/22 14:39:02 slr6053 Exp $
    class ThreadsWindow extends JFrame implements Runnable, ActionListener {
       private JTextPane textArea ;
       private JButton startStop, closeBtn ;
       private boolean updateInformation = true ;
       private boolean exitThread = false ;
       private Document doc;
       private SimpleAttributeSet att;
       private SimpleAttributeSet attRed;
       private SimpleAttributeSet attBold;
       private SimpleAttributeSet attBold1;
        * Create and show a window that will display the Threads used in the
        * current JVM. The display will be updated every second from a newly
        * created Thread "SEE Threads".
        * @param title The window title for the window.
       public ThreadsWindow( String title ) {
          super( title ) ;
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          textArea = new JTextPane() ;
          att    = new SimpleAttributeSet();
          attBold1 = new SimpleAttributeSet( att );
          StyleConstants.setBold( attBold1, true );
          StyleConstants.setFontSize( attBold1, 14 );
          attBold = new SimpleAttributeSet( att );
          StyleConstants.setBold( attBold, true );
          attRed = new SimpleAttributeSet();
          StyleConstants.setForeground( attRed, Color.red);
          StyleConstants.setBold( attRed, true );
          doc = textArea.getStyledDocument();
          getContentPane().setLayout( new BorderLayout() ) ;
          getContentPane().add( new JScrollPane().add(
                 new JPanel().add( textArea ) ), BorderLayout.CENTER ) ;
          startStop = new JButton( "Start/Stop" ) ;
          closeBtn = new JButton( "CLOSE" ) ;
          JPanel buttons = new JPanel() ;
          buttons.setLayout( new GridLayout( 0, 2 ) ) ;
          buttons.add( startStop ) ;
          buttons.add( closeBtn ) ;
          startStop.addActionListener( this ) ;
          closeBtn.addActionListener( this ) ;
          getContentPane().add( buttons, BorderLayout.NORTH ) ;
          setSize( 300, 400 ) ;
       } // end of constructor()
        * Handle the buttons.
       public void actionPerformed( ActionEvent e ) {
          Object srcIn = e.getSource() ;
          if( srcIn instanceof JButton ) {
             JButton src = (JButton)srcIn ;
             if( src == startStop ) {
                updateInformation = !updateInformation ;
             } else if( src == closeBtn ) {
                updateInformation = false ;
                exitThread = true ;
                setVisible( true ) ;
                dispose() ;
             } // end else if
          } // end if
       } // end of actionPerformed()
        * While true, sleep 1 second and then repaint.
       public void run() {
          while( !exitThread ) {            // do forever
             if ( Test.isCondition()  ) {
                setVisible( true );
                try {
                   Thread.sleep( 1000 ); // update every second
                } catch ( Exception sEx ) {
                if ( updateInformation )
                   repaint();
             } // end if
          } // end while
       } // end of run()
        * Display the hierarchy of Thread-Groups and Threads.
       public void paint( Graphics g ) {
          super.paint( g ) ;
          if( updateInformation ) {
             try {
                doc.remove(  0, doc.getLength() );
                doc.insertString( 0, "THREAD INFORMATION: " +
                               UtSys.datTimSec() + "\n", attBold1 ) ;
             } catch ( BadLocationException e1 ) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
             ThreadGroup rootT = Thread.currentThread().getThreadGroup();
             while( rootT.getParent() != null ) {
                rootT = rootT.getParent();
             }// end while
             try {
                buildThreadOutput( rootT, "" ) ;
             } catch ( BadLocationException e ) {
                // TODO Auto-generated catch block
                e.printStackTrace();
          } // end if
       } // end of paint()
        * Append to the textArea variable the passed ThreadGroup and any
        * Threads it contains. If it contains ant ThreadGroups, invoke this
        * method recursively on each of these threadGroups, etc...
        * @param tg The ThreadGroup to display
        * @param indent The indent-level String to preface each line with.
        *        This method appends "-+" to this String and passes it to the
        *        next recursive invocation.
        * @throws BadLocationException
       private void buildThreadOutput( ThreadGroup tg, String indent ) throws BadLocationException {
          doc.insertString( doc.getLength(),  "   ThreadGroup " +
                           "\"" + tg.getName() + "\":" +
                           " Max Priority = " + tg.getMaxPriority() +
                            "\n", attBold );
          indent = "      ";
          Thread threadArray[] = new Thread[ tg.activeCount() ];
          int threadCount = tg.enumerate( threadArray, false );
          for( int i = 0; i < threadCount; i++ ) {   // THREADS
             Thread thread = threadArray;
    doc.insertString( doc.getLength(), indent + thread.getId()+" "+
    " \"" +thread.getName() +
    "\" Priority=" + thread.getPriority() +
    " Daemon=" + thread.isDaemon() +
    " Active= "+ thread.isAlive() +
    " Interuppted= "+ thread.isInterrupted() +
    "\n", att ) ;
    } // end for
    ThreadGroup threadGroupArray[] = new ThreadGroup[
    tg.activeGroupCount() ];
    int threadGroupCount = tg.enumerate( threadGroupArray, false );
    for( int i = 0; i < threadGroupCount; i++ ) { // THREADGROUPS
    buildThreadOutput( threadGroupArray[i], indent ) ;
    } // end for
    } // end of buildThreadOutput
    } // end of ThreadsWindow class

  • Using BufferedReader with a web form

    I am importing a fixed length txt file into our database from the web.
    My process code looks like:
    java.io.BufferedReader r=request.getReader();
    java.io.BufferedReader br=new java.io.BufferedReader(r);
    String currentRow = "";
    StringBuffer fileBody=new StringBuffer(1000);
         while((currentRow=br.readLine().trim())!=null) {
              out.print(currentRow + "<BR>");
              br.close();
    It works okay, but I also get all field names and extra info from the form that looks like this:
    -----------------------------11955629961970272440171062340
    Content-Disposition: form-data; name="file_body"; filename="opudiskMiniEMC.txt"
    Content-Type: text/plain
    How can I get just the content of the text file?
    Thanks,
    Evan

    sounds like you are doing multipart POST ... you should get UploadBean or Jakarta Commons File Uploader which will process those out for you...
    However, every field will start with a separator. The separator is defined at the top of the stream. After the separator is a newline and some header info and a blank line. After the blank line to the next separator is the data for that field. Such is the format of multipart/form-data.

  • Reading from home directory in linux using ~/ or $HOME and BufferedReader

    I'm working on an app that reads in a number from a user's home directory using BufferedReader. The file is written by an external script to ~/filename. I don't know if the user of the app's home directory will be /homes/username, /home/username, or something else. I would prefer to read in a similar fashion:
    BufferedReader in = new BufferedReader( new FileReader("~" + File.separator + ".AppDisableUntilDate") );
    Unfortunately, this causes the following error:
    java.io.FileNotFoundException: ~/.AppDisableUntilDate (No such file or directory)
    less ~/.AppDisableUntilDate does read the file. Using $HOME in place of ~/ also fails. Any ideas what might work?
    Thanks,
    Joel

    ~ is understood only by the shell. And not by every shell either.
    Korn and Bourne-again shell (ksh and bash) understand it, I would conjecture, Bourne shell (good old sh) does not.

  • Performance slow using url BufferedReader

    I'm reading the contents of a url using BufferedReader, it takes a while to read the url into my application, what could be done to speed it up. Here's the code.
    DiscovererUrl = https://url_to_site
    URL myurl = new URL(DiscovererUrl);
    HttpURLConnection con = (HttpURLConnection)myurl.openConnection();
    InputStream ins = con.getInputStream();
    InputStreamReader isr=new InputStreamReader(ins);
    BufferedReader in =new BufferedReader(isr);
    StringBuffer inputLine=null;
    StringBuffer entirehtml=new StringBuffer();
    String entirehtmlafter = "";
    StringBuffer str = null;
    StringBuffer str2 = null;
    try{
    while ((inputLine = new StringBuffer(in.readLine())) != null)
    entirehtml.append(inputLine);
    catch (NullPointerException npe){}
    in.close();
    isr.close();
    ins.close();
    con.disconnect();

    it takes a while to read the url into my applicationWhat is 'a while'? Maybe it's because the site is not responding fast anyway.
    Don't forget that with SSL it's slower.
    By the way, you don't need to instantiate a StringBuffer for each line read:
    while ((inputLine = in.readLine()) != null)
        entirehtml.append(inputLine);

  • Help using scanner class to count chars in file

    Hi all, I am learning Java right now and ran into a problem. I need to use the Scanner class to accurately count the number of chars in a file including the line feed chars 10&13.
    This what I have and it currently reports a 201 byte file as having 194 chars:
         File file = new File(plainFile);
         Scanner inputFile = new Scanner(file);
         numberOfChars = 0;
         String line;
         //count characters in file
         while (inputFile.hasNextLine())
              line = inputFile.nextLine();
              numberOfChars += line.length();
    I know there are other ways using BufferedReader, etc but I have to use Scanner class to do this.
    Thanks in advance!

    raichle wrote:
    Wow guys, thanks for the help! I've got a RTFMWell, what's wrong to have a look at the API docs for the Scanner class?
    and directions that go against the specs I said.Is that so strange to suggest a better option? What if I ask a carpenter "how do I build a table with a my stapler?". Should I give the man an attitude if he tells me I'd better use a saw and hammer?
    I'm also aware that it "eats" those chars and obviously looking for a way around that.
    I've looked through the java docs, but as I said, I'm new to this and they're difficult to understand. The class I am auditing req's that this be done using Scanner, but I don't see why you demand an explanation.
    Can anybody give me some constructive help?Get lost?

  • Monitoring a Process using Runtime.exce()

    Hi,
    In my Program, I'm using the
    new BufferedReader(new InputStreamReader(Runtime.getRuntime()                         .exec("ps -ef | grep xmlfeed").getInputStream()));
    The above statement is not returning any inputstream to the BuffredReader.
    When I gave the command as "PWD", it's returning the lines as expected.
    But it's not working even for "PS" command also.I'm running this in AIX machine.
    Any Ideas,Please help....
    Edited by: haijdp on Dec 21, 2007 1:11 AM

    Hello! And sorry I didn't reply earlier. I hope the Original Poster will find revisit this thread and it helps him.
    From your post I assumed that you were not a student trying to create some homework. That's why I felt free to simply code a solution and submit the code here. But first some remarks:
    I don't think that your code can work. Runtime.exec expects an array of type String, where the first element is the command and subsequent elements are a command line option each. I don't think you can use the pipe and call several commands using Runtime.exec, but that's just a kind of guess. YMMV.
    Running external Processes in Java is a bit complicated. Basically,
    * It's good to run the process in it's own thread. That way the main program can continue without getting stuck.
    * To extract stdout and stderr of your target process you must run two threads, one for stderr and one for stdout. Both threads extract the characters of their respective streams in a loop that runs inside the thread. Again, that way we avoid deadlocks, program getting stuck etc.
    This explanation is terrible, I know - I think a slice of source code speaks louder than words. I have attached five java files which together make a little process runner which extracts stdout and stderr in a safe manner. To run:
    * Cut'n paste them into five text files, one per class.
    * Save the each text file as {contained-class-name}.java
    * Compile the stuff
    * Run RunnerDemo (When I ran it, I got a directory listing printed on the console)
    Explanation sounds a bit sloppy, but I did it under the assumption that you are a seasoned java pro, so it should not pose any problems. Since you seem to be a different OS than I (AIX, I run Linux), the command may or may not work. Try other commands. For example, in the RunnerDemo class you could set the cmd field to this:
            String [] cmd =
                "ps",
                "-A",
                "-H"
            };This would give you a process listing (works on Linux).
    By the way, commands are passed as array. See Java documentation for java.lang.Runtime.exec (String []) for explanation of this array.
    One problem I see in your command is that the output of ps is piped to some other program. Sorry, I don't know whether my code could achieve this. All it can do is to rum one single command with command line options. But you should be able to adjust the given example, so it supports piping to another program.
    If you have any further questions, please don't hesitate to ask!
    Class: RunnerDemo
    *                           RunnerDemo.java
    *                     Demo for the process runner
    package rtimeexec;
    public class RunnerDemo
        public static void main (String [] args)
            String [] cmd =
                "ls",
                "-a",
                "-l"
            ProcessRunner   runner;
            String          stdOutStr;
            String          stdErrStr;
            runner = new ProcessRunner (cmd);
            runner.start ();
            runner.BlockUntilFinished ();
            stdOutStr = runner.GetStdOutText ();
            stdErrStr = runner.GetStdErrText ();
            System.out.println ("Process result, ls -a -l");
            System.out.println ("-----------------------------------------------------------------------");
            System.out.println ("Stdout:");
            System.out.println ("-----------------------------------------------------------------------");
            System.out.println (stdOutStr);
            System.out.println ();
            System.out.println ("-----------------------------------------------------------------------");
            System.out.println ("Stderr:");
            System.out.println ("-----------------------------------------------------------------------");
            System.out.println (stdErrStr);
    Class: ProcessRunner
    package rtimeexec;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    * Runs a system process and extracts stdout and stderr of that process.
    * Process will run in its own thread, so that the caller can simply continue
    * with less of a chance to get locked down. Caller can invoke the {@link BlockUntilFinished}
    * method after starting this thread. This method blocks until the thread is finished,
    * i.e. the process has finished.
    * Unfortunately, we haven't implemented any facility to stream characters to
    * stdin of the process called. If that facility would exist we could refactor
    * the classes and realize some sort of piping facility, as it's possible in
    * Linux, for example.
    * Example on how to run a process:
    * <pre>
    * String []         cmd  = {"ps", "-AH"};
    * String            sOut;
    * String            sErr;
    * ProcessRunner     runner;
    * runner = new ProcessRunner (cmd);
    * runner.start ();
    * runner.BlockUntilFinished ();
    * sOut = runner.GetStdOutText ();
    * sErr = runner.GetStdErrText ();
    * System.out.println ("Stdout:");
    * System.out.println (sOut);
    * System.out.println ("------------------------------------------------------");
    * System.out.println ("Stderr:");
    * System.out.println (sErr);
    * </pre>
    public class ProcessRunner extends Thread
        private String []                   command;
        private int                         execResult;
        private String                      stdOutText;
        private String                      stdErrText;
        private boolean                     isFinished;
        public ProcessRunner (String [] cmd)
            command     = cmd;
            execResult  = 0;
            stdOutText  = null;
            stdErrText  = null;
            isFinished  = false;
        public int GetResult ()
            return execResult;
        public String GetStdOutText ()
            return stdOutText;
        public String GetStdErrText ()
            return stdErrText;
        public boolean IsFinished ()
            return isFinished;
        public void BlockUntilFinished ()
            while (! isFinished)
                try {Thread.sleep (250);} catch (InterruptedException e) {}
        public void run ()
            Process         proc;
            Runtime         rt;
            InputStream     stdOut;
            InputStream     stdErr;
            CharStream      stdOutEx;
            CharStream      stdErrEx;
            int             res;
            isFinished = false;
            try
                res         = 0;
                rt          = Runtime.getRuntime ;       ();
                proc        = rt.exec ;                  (command);
                stdOut      = proc.getInputStream ;      ();
                stdErr      = proc.getErrorStream ;      ();
                stdOutEx    = new CharStream            (stdOut);
                stdErrEx    = new CharStream            (stdErr);
                stdOutEx.start ();
                stdErrEx.start ();
                try {res = proc.waitFor ();} catch (InterruptedException e) {}
                // Process has finished; now wait until any buffers are empty.
                stdOutEx.BlockUntilFinished ();
                stdErrEx.BlockUntilFinished ();
                stdOutText = stdOutEx.GetResult ();
                stdErrText = stdErrEx.GetResult ();
                execResult = res;
            catch (IOException e)
                isFinished = true;
                throw new ExtractionException (e.getLocalizedMessage());
            isFinished = true;
    Class: CharStream
    package rtimeexec;
    import java.io.IOException;
    import java.io.InputStream;
    * A Character extractor. Extracts characters from a stream and puts them
    * into a String. To protect from memory overflow we put a limit in place.
    * When storage demads exceed that limit, an exception is thrown.
    public class CharStream extends Thread
        private static final int    maxChunkLen         = 8192;
        private static final int    maxStorageSize      = 512 * 1024;   // 512 KBytes
        private InputStream     sourceStream;
        private StringBuffer    extracted;
        private boolean         isFinished;
        public CharStream (InputStream istream)
            sourceStream    = istream;
            extracted       = new StringBuffer ();
            isFinished      = false;
        public String GetResult ()
            String ret;
            ret = extracted.toString ();
            return ret;
        public void BlockUntilFinished ()
            while (! isFinished)
                SleepThread (250);
        public void run ()
            byte []                 buffer;
            int                     nBytesRead;
            byte                    b;
            char                    c;
            int                     iChar;
            int                     nCharsTotal;
            boolean                 isEOF;
            isEOF       = false;
            nCharsTotal = 0;
            isFinished = false;
            while (! isEOF)
                try
                    buffer      = new byte [maxChunkLen];
                    nBytesRead  = sourceStream.read (buffer);
                    if (nBytesRead >= 1)
                    {   // much faster stream extraction method than when we use
                        // BufferedReader(new InputStreamReader(sourceStream)).
                        for (iChar = 0; iChar < nBytesRead; iChar++)
                            nCharsTotal++;
                            if (nCharsTotal > maxStorageSize)
                                throw new StoreFullException
                                    "Storage limit exceeded (" + Integer.toString (maxChunkLen) + "Bytes)"
                            b = buffer [iChar];
                            c = (char) b;
                            extracted.append (c);
                    else if (nBytesRead <= -1)
                        isEOF       = true;
                catch (IOException e)
                    isFinished = true;
                    throw new ExtractionException (e.getLocalizedMessage());
                SleepThread (250);
            isFinished  = true;
        private void SleepThread (int mSec)
            try
                Thread.sleep (mSec);
            catch (InterruptedException e)
    Class: StoreFullException
    package rtimeexec;
    * Exception that gets thrown when a storage container is full.
    public class StoreFullException extends RuntimeException
        private static final long serialVersionUID = - 4996246591135389009L;
        public StoreFullException (String message)
            super (message);
    Class: ExtractionException
    package rtimeexec;
    * Thrown when there was some problem during stream extraction.
    public class ExtractionException extends RuntimeException
        private static final long serialVersionUID = - 6124525536783450209L;
        public ExtractionException (String message)
            super (message);
    }

Maybe you are looking for