How to display Runtime.exec() command line output via swing

Hi all, I'm new to java but have a pretty good understanding of it. I'm just not familiar with all the different classes. I'm having trouble capturing the output from a command I'm running from my program. I'm using Runtime.exec(cmdarray) and I'm trying to display the output/results to a JFrame. Once I get the output to display in a JFrame, I'd like it to be almost like a java command prompt where I can type into it incase the command requires user interaction.
The command executes fine, but I just don't know how to get the results of the command when executed. The command is executed when I click a JButton, which I'd like to then open a JFrame, Popup window or something to display the command results while allowing user interaction.
Any examples would be appreciated.
Thank you for your help in advance and I apologize if I'm not clear.

You can get the standard output of the program with Process.getInputStream. (It's output from the process, but input to your program.)
This assumes of course that the program you're running is a console program that reads/writes to standard input/output.
In fact, you really should read from standard output and standard error from the process you start, even if you're not planning to use them. Read this:
When Runtime Exec Won't

Similar Messages

  • How can I run Runtime.exec command in Java To invoke several other javas?

    Dear Friends:
    I met a problem when I want to use a Java program to run other java processes by Runtime.exec command,
    How can I run Runtime.exec command in Java To invoke several other java processes??
    see code below,
    I want to use HelloHappyCall to call both HappyHoliday.java and HellowWorld.java,
    [1]. main program,
    package abc;
    import java.util.*;
    import java.io.*;
    class HelloHappyCall
         public static void main(String[] args){
              try
                   Runtime.getRuntime().exec("java  -version");
                   Runtime.getRuntime().exec("cmd /c java  HelloWorld "); // here start will create a new process..
                   System.out.println("Never mind abt the bach file execution...");
              catch(Exception ex)
                   System.out.println("Exception occured: " + ex);
    } [2]. sub 1 program
    package abc;
    import java.util.*;
    import java.io.*;
    class HelloWorld
         public static void main(String[] args){
         System.out.println("Hellow World");
    } [3]. Sub 2 program:
    package abc;
    import java.util.*;
    import java.io.*;
    class HappyHoliday
         public static void main(String[] args){
         System.out.println("Happy Holiday!!");
    } When I run, I got following:
    Never mind abt the bach file execution...
    I cannot see both Java version and Hellow World print, what is wrong??
    I use eclipse3.2
    Thanks a lot..

    sunnymanman wrote:
    Thanks,
    But How can I see both programs printout
    "Happy Holiday"
    and
    "Hello World"
    ??First of all, you're not even calling the Happy Holiday one. If you want it to do something, you have to invoke it.
    And by the way, in your comments, you mention that in one case, a new process is created. Actually, new processes are created each time you call Runtime.exec.
    Anyway, if you want the output from the processes, you read it using getInputStream from the Process class. In fact, you really should read that stream anyway (read that URL I sent you to find out why).
    If you want to print that output to the screen, then do so as you'd print anything to the screen.
    in notepad HelloWorld.java, I can see it is opened,
    but in Java, not.I have no idea what you're saying here. It's not relevant whether a source code file is opened in Notepad, when running a program.

  • Runtime.exec(command)

    hi experts,
    I am trying to execute a set of commands from java program
    eg: from command prompt
    java CommandExecutor c:\winnt\notepad.exe c:\some.exe c:\onemorecommand.exe
    and inside the CommandExecutor main method..
    public static void main(String []arg)
    for(i = 0; i < arg.length; i++)
    Runtime.getRuntime().exec(arg(i));
    the above code is executing all the command one after the other, but I want to execute the above commands squentially, i.e I want to execute the second command only after finishing the first command and the third after finishing the second and so on depending upon the arguments passed, how can I acheive this...
    I have tried to use the Process which is returned by the exec(arg) method but the exitValue() returns same value before execution and after execution.
    thanks,
    krishna

    This is the code I use for this very purpose and it works great. Here you go:
    * Wrapper for Runtime.exec
    * No console output is generated for the command executed.
    * Use <code>process.getOutputStream()</code> to write data out that will be used as
    * input to the process. Don't forget to include <code>\n</code> <code>\r</code>
    * characters the process is expecting.
    * Use <code>process.getInputStream</code> to get the data the process squirts out to
    * stdout.
    * It is recommended to wrap this call into a seperate thread as to not lock up the
    * main AWT event processing thread. (generally seperate threads are needed for both
    * the STDOUT and STDIN to avoid deadlock)
    * @param theCommand fully qualified #.exe or *.com command for windows etc.
    * @see   exec, shell, command, cmd, forDOS, forNT
    public static Process exec( String theCommand, boolean wait )
         Process process;
         try
              process = Runtime.getRuntime().exec( theCommand );
         catch ( IOException theException )
              return null;
         if ( wait )
              try
                   process.waitFor();
              catch ( InterruptedException theInterruptedException )
         return process;
    }

  • Capturing command line output to a file possible?

    Hi, i am in need of capturing the command line output to a txt file and need some suggestions on how to do it.
    I have two classes, class A is the one with all the methods and outputs text to the command line (using System.out.print). class B is the one that calls the methods and needs to record the command line output to a file.
    Now the problem i face is not all the output is going to be written to a file and not all the output is going to be displayed on the command line. eg. class B will have a way to select the output mode which is either both to a file and command line or just to a file and display nothing on the command line.
    Is what i am asking even possible? Any suggestions would be great!

    Here is a class I found on the forum that does basically what you need. Just change the code that is updating a Document to write to a file:
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class ConsoleOutputStream extends OutputStream
         private Document document = null;
         private ByteArrayOutputStream outputStream = new ByteArrayOutputStream(256);
         private PrintStream ps = null;
         public ConsoleOutputStream(Document document, PrintStream ps)
              this.document = document;
              this.ps = ps;
         public void write(int b)
              outputStream.write (b);
         public void flush() throws IOException
              super.flush();
              try
                   if (document != null)
                        document.insertString (document.getLength (),
                             new String (outputStream.toByteArray ()), null);
                   if (ps != null)
                        ps.write (outputStream.toByteArray ());
                   outputStream.reset ();
              catch(Exception e) {}
         public static void main(String[] args)
              JTextArea textArea = new JTextArea();
              JScrollPane scrollPane = new JScrollPane( textArea );
              JFrame frame = new JFrame("Redirect Output");
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.getContentPane().add( scrollPane );
              frame.setSize(300, 600);
              frame.setVisible(true);
              System.setOut( new PrintStream(
                   new ConsoleOutputStream (textArea.getDocument (), System.out), true));
              System.setErr( new PrintStream(
                   new ConsoleOutputStream (textArea.getDocument (), null), true));
              Timer timer = new Timer(1000, new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        System.out.println( new java.util.Date().toString() );
                        System.err.println( System.currentTimeMillis() );
              timer.start();
    }

  • How to set SAXParser at command-line interface to create a large XML file

    Hi,
    I am trying to create a large XML file (more than 50 MB) by selecting from Oracle database but failed because of "out of memory" error. According to "Oracle XML Developer Guide", we should use SAXParser to parsing a large XML file. But there is no example to show how to set SAXParser at command-line
    Following is what I use to get xml files. It works only when the file is small.
    java OracleXML getXML -DateFormat -withDTD -rowsetTag PO_HDR -conn
    "jdbc:oracle:oci8:@server_name" -user "ID/password" "select * from table_name"
    When I set SAXParser at the way below,
    java oracle.xml.parser.v2.SAXParser OracleXML getXML -DateFormat -withDTD -rowsetTag PO_HDR -conn
    "jdbc:oracle:oci8:@server_name" -user "ID/password" "select * from table_name"
    it failed with the error message: "In class oracle.xml.parser.v2.SAXParser: void main(String argv[]) is not defined"
    Does anyone know how to solve the problem? I'll be appreciated very much for your help.
    Yi

    here are my ideas.
    register the xml schema.
    using xmldom, generate the desired xml output and return as xmltype.
    then you can use something like this to check.
    declare
    xmldoc xmltype ;
    begin
       -- populate xmldoc from you xmldom function
       -- validate against XML schema
       xmldoc.isSchemaValid(schema_url, root_element);
       if xmldoc.isSchemaValid = 1 then
            --valid schema
       else
            --invalid
       end if;
    end

  • How can I use srvctl command line for change "Failover type" and "F method"

    Hi all,
    I am using Oracle One Node (11.2.0.3), and I have a service:
    /u01/11.2.0/grid/bin/srvctl config service -d orcl
    Service name: orcldb
    Service is enabled
    Server pool: orcl
    Cardinality: 1
    Disconnect: false
    Service role: PRIMARY
    Management policy: AUTOMATIC
    DTP transaction: false
    AQ HA notifications: false
    Failover type: NONE
    Failover method: NONE
    TAF failover retries: 0
    TAF failover delay: 0
    Connection Load Balancing Goal: LONG
    Runtime Load Balancing Goal: NONE
    TAF policy specification: BASIC
    Edition:
    Preferred instances: orcl_1
    Available instances:
    I would like to change "Failover type" and "Failover method" to:
    Failover type: SELECT
    Failover method: BASIC
    How can I do that? Is there any graphical tool for it? Or, How can I use srvctl command line for change it?
    Thanks in advance.
    Leonardo.

    user10674190 wrote:
    Hi all,
    I am using Oracle One Node (11.2.0.3), and I have a service:
    /u01/11.2.0/grid/bin/srvctl config service -d orcl
    Service name: orcldb
    Service is enabled
    Server pool: orcl
    Cardinality: 1
    Disconnect: false
    Service role: PRIMARY
    Management policy: AUTOMATIC
    DTP transaction: false
    AQ HA notifications: false
    Failover type: NONE
    Failover method: NONE
    TAF failover retries: 0
    TAF failover delay: 0
    Connection Load Balancing Goal: LONG
    Runtime Load Balancing Goal: NONE
    TAF policy specification: BASIC
    Edition:
    Preferred instances: orcl_1
    Available instances:
    I would like to change "Failover type" and "Failover method" to:
    Failover type: SELECT
    Failover method: BASIC
    How can I do that? Is there any graphical tool for it? Or, How can I use srvctl command line for change it?
    Thanks in advance.
    Leonardo.srvctl modify service -d database_name -s orcldb -q TRUE -m BASIC -P BASIC -e SELECT -z 180 -w 5 -j LONG
    Also see
    11gR2(11.2) RAC TAF Configuration for Admin and Policy Managed Databases [ID 1312749.1]

  • How to display polygons both with line contour and filled interior?

    How to display polygons both with line contour and filled interior?
    Java3D 1.3, Java 1.4.1-rc

    Hi,
    I just started with Java3D last week.
    I assume you mean drawing polygons with outlines (wireframe) in one color and polygon face filling with another color. If so, I've got the same question! (I usually think of "contour" to refers to plotting surface intensity of independent data like temperature or elevation, but I don't think you mean this.)
    The only solution I've found so far is to make two shapes with the same geometry.
    Here's an example - an outlined and filled cube. I made it using a generalize class DualShape which is two shapes with the same geometry, but one filled and one as a line.
    It works, although I can't say I understand the setPolygonOffset(), knowing what value to set. Without the command, the depthbuffer can't consistently decide which should be in front between the fills and lines so it looks bad.
    I certainly think it would be nicer to do both internally, like:
    pa.setPolygonMode(pa.POLYGON_LINE || pa.POLYGON_FILL);
    And then have setFillColor and setLineColor for each.
    I don't know why they don't allow this - maybe OpenGL can't do it like this so Java3D follows.
    If anyone has any better ideas I'd like to hear about it.
    Tom Ruen
    class DualCube extends DualShape // cube with outline and fill colors
    public DualCube(float ax, float ay, float az, //cube lower corner
    float bx, float by, float bz, //cube upper corner
    float br, float bg, float bb, //border color
    float fr, float fg, float fb) //fill color
    setGeometry(new CubeGeometry(ax,ay,az,bx,by,bz),br,bg,bb,fr,fg,fb);
    class DualShape extends BranchGroup //general shape with outline and fill colors
    Appearance ap1,ap2;
    PolygonAttributes pa1,pa2;
    ColoringAttributes ca1,ca2;
    Shape3D s1,s2;
    public void setGeometry(Geometry geo, float br, float bg, float bb, float fr, float fg, float fb)
    //filled shape:
    addChild(s1=new Shape3D(geo, ap1=new Appearance()));
    ap1.setPolygonAttributes(pa1=new PolygonAttributes()); pa1.setPolygonMode(pa1.POLYGON_FILL);
    ap1.setColoringAttributes(ca1=new ColoringAttributes()); ca1.setColor(fr,fg,fb);
    //lined (wire) shape:
    addChild(s2=new Shape3D(geo, ap2=new Appearance()));
    ap2.setPolygonAttributes(pa2=new PolygonAttributes()); pa2.setPolygonMode(pa2.POLYGON_LINE);
    ap2.setColoringAttributes(ca2=new ColoringAttributes()); ca2.setColor(br,bg,bb);
    pa2.setPolygonOffset(-1000); //Uncertain what "float" value to use!
    class CubeGeometry extends IndexedQuadArray //cube geometry data
    private static final int[] faces =
    0,3,2,1,
    0,1,5,4,
    1,2,6,5,
    2,3,7,6,
    3,0,4,7,
    4,5,6,7
    private static float[] verts = new float[24];
    public CubeGeometry(float ax, float ay, float az, //lower limit
    float bx, float by, float bz) //upper limit
    super(8, IndexedQuadArray.COORDINATES , 24);
    int n;
    n=0; verts[n]=ax; verts[n+1]=ay; verts[n+2]=az;
    n=3; verts[n]=bx; verts[n+1]=ay; verts[n+2]=az;
    n=6; verts[n]=bx; verts[n+1]=by; verts[n+2]=az;
    n=9; verts[n]=ax; verts[n+1]=by; verts[n+2]=az;
    n=12; verts[n]=ax; verts[n+1]=ay; verts[n+2]=bz;
    n=15; verts[n]=bx; verts[n+1]=ay; verts[n+2]=bz;
    n=18; verts[n]=bx; verts[n+1]=by; verts[n+2]=bz;
    n=21; verts[n]=ax; verts[n+1]=by; verts[n+2]=bz;
    setCoordinates(0, verts);
    setCoordinateIndices(0, faces);

  • Feedback from runtime.exec(command)

    Hi,
    I hope someone can point out the problem with the following. I have a method that is supposed to execute a shell command. The shell command would look something like the following:
    serctl add 351 password [email protected]
    However when this command is executed in a shell/command line a prompt is shown ("MySql password:")asking for a password. Once the user enters the password, the user is added. My code currently executes the first half of the command but gets stuck on the password prompt. My code stops by the line "before the loop" and never enters the inner loop. So obviously my code isn't working properly to say that if the response is a password prompt, to pass it the password variable.
    Any ideas?
    Many Thanks.
    void addUser(String username, String password, String email, String passwd, HttpServletResponse response) throws IOException {
       String[] command = {"serctl", "add", username, password, email};
       //String[] command = {"pstree"};
       Runtime runtime = Runtime.getRuntime();
       Process process = null;
       response.setContentType(CONTENT_TYPE);
       PrintWriter out = response.getWriter();
       String s = "something";
       try {
         process = runtime.exec(command);
         System.out.println("Process is: " + process);
         System.out.println("Command is: " + command);
         BufferedReader in =
         new BufferedReader(new InputStreamReader(process.getInputStream()));
         BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
         OutputStream stdout = process.getOutputStream();
         System.out.println("before the loop");
         s=in.readLine();
         System.out.println(s);
         System.out.println(s);
         System.out.println(in);
         System.out.println(stdout);
         //while((s=in.readLine())!= null)
         while((s=in.readLine()).equals("MySql password: "))
           //s = in.readLine();
           System.out.println(in.readLine());
           System.out.println(s);
           out.println(s);
           if (s.equals("MySql password:  ")) {
             System.out.println("Must be equal to MySql password;");
             //stdout.write(passwd.getBytes());
             //stdout.write(adminpassword);
             //stdout.flush();
             //break;
        System.out.println("after the loop");
         System.out.println("Here is the standard error of the command(if any):\n");
         while ((s = error.readLine()) != null){
           System.out.println(s);
         stdout.close();
         in.close();
         error.close();
         out.println(in);
         out.println("<html>");
         out.println("<body bgcolor=\"#FFFCCC\">");
         out.println("You have successfully added a new user.<br><br>");
         out.println("User " + username + " has been created ");
         out.println("</body></html>");
        catch (Exception e) {
              System.out.println("Uh oh! Error adding new user.");
              e.printStackTrace();
    }

    Just a random observation:
    Sometimes programs that prompt for passwords do it in a way that is impossible to redirect (or at least requires special trickery, such as creating a pseudo-TTY). E.g. in Unix this involves opening /dev/tty and using that instead of stdout & stdin. This is done to make sure there really is a person who knows the password sitting there in front of the teletype.
    I don't know if the "serctl" program does that. If stdout&stdin redirection does not appear to work then it is a possibility.
    A quick googling for "serctl" reveals:
    Commands labeled with (*) will prompt for a MySQL password.
    If the variable PW is set, the password will not be prompted.
    which might or might not be an easier way to deal with this particular program. If it indeed is the same "serctl" program.

  • Running jar in unix using runtime exec command

    Hi, i want to run a jar in unix with the runtime.exec() command,
    but i couldn't manage to do it
    Here is the code
    dene = new String[] {"command","pwd","java tr.com.meteksan.pdocs.pdf.html2pdf "+ f.getAbsolutePath() + " " + pdfPath};
              System.out.println("Creating PDF");
              FileOutputStream fos = new FileOutputStream(new File(pdfPath));
              Runtime rt = Runtime.getRuntime();
              for(int i = 0 ; i < dene.length ; i++)
                  System.out.println("komut = "+dene);
              Process proc = rt.exec(dene);
              // any error message?
              StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); // any output?
              StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT", fos); // kick them off
              errorGobbler.start();
              outputGobbler.start();
              // any error???
              int exitVal = proc.waitFor();
              System.out.println("ExitValue: " + exitVal);
              fos.flush();
              fos.close();
    when i run this program, the exit value of the process is 0
    can you tell me whats wrong?

    i changed the string to be executed to:
                             dene = new String[] {"sh","-c","java -classpath \"" + Sabit.PDF_TOOL_PATH
                                  + "avalon-framework-4.2.0.jar:" + "" + Sabit.PDF_TOOL_PATH
                                  + "batik-all-1.6.jar:" + Sabit.PDF_TOOL_PATH
                                  + "commons-io-1.1.jar:" + Sabit.PDF_TOOL_PATH
                                  + "commons-logging-1.0.4.jar:" + "" + Sabit.PDF_TOOL_PATH
                                  + "fop.jar:" + Sabit.PDF_TOOL_PATH + "serializer-2.7.0.jar:"
                                  + Sabit.PDF_TOOL_PATH + "Tidy.jar:" + Sabit.PDF_TOOL_PATH
                                  + "xalan-2.7.0.jar:" + "" + Sabit.PDF_TOOL_PATH
                                  + "xercesImpl-2.7.1.jar:" + Sabit.PDF_TOOL_PATH
                                  + "xml-apis-1.3.02.jar:" + Sabit.PDF_TOOL_PATH
                                  + "xmlgraphics-commons-1.0.jar:" + "" + Sabit.PDF_TOOL_PATH
                                  + "html2pdf.jar:\" tr.com.meteksan.pdocs.pdf.html2pdf "
                                  + f.getAbsolutePath() + " " + pdfPath};     
    and it works now ;)
    thanks...

  • How to display the fields in ALV Output without using Field catalog?

    How to display the fields in ALV Output without using Field catalog?
    Could you pls tell me the coding?
    Akshitha.

    Hi,
    u mean without building field catalog. is it? I that case, we can use the FM REUSE_ALV_FIELDCATALOG_MERGE.
    data: itab type table of mara.
    CALL FUNCTION 'REUSE_ALV_FIELDCATALOG_MERGE'
    EXPORTING
    i_program_name = sy-repid
    i_structure_name = itab
    CHANGING
    ct_fieldcat = lt_fieldcat[]
    EXCEPTIONS
    inconsistent_interface = 1
    program_error = 2
    OTHERS = 3.
    *Pass that field catalog into the fillowing FM
    call function 'REUSE_ALV_GRID_DISPLAY'
           exporting
                i_callback_program      = gd_repid
                i_grid_title            = 'REPORTING'
                is_layout              = gt_layout
                it_fieldcat             = lt_fieldcat[]
           tables
                t_outtab                = itab.

  • How do you put a command line in adobe illustrator?

    how do you put a command line in adobe illustrator?

    Your question makes no sense. What exactly are you trying to do?

  • How can I deploy by command line on AS 10.1.3?

    I have used oracle AS 10.1.3.
    I have created ear file from command line.
    But I don't know how i can deploy by command line?
    However i can deploy from Web manage.
    So, Please tell me How i can deploy by command line when i want?
    Thx

    Hello,
    In OracleAS 10g R3 (10.1.3.x) you can deploy by command line using the admin_client.jar utility, that is exposed also as Apache Ant tasks. In 10.1.3.x you can use the same tool to deploy in a single stand alone OC4J instance to a multi-nodees cluster managed by OPMN.
    Here the documentation about this utility:
    - Deployment Guide
    - Deploying with the admin_client.jar Utility
    -Deploying with the OC4J Ant Tasks
    Regards
    Tugdual Grall

  • How to display multiple tables from database using netbeans swing gui

    plz reply asap on how to display multiple tables from database using netbeans swing gui into the same project

    Layered Pane with JTables or you can easily to it with a little scripting and HTML.
    plzzzzzzzzzzzzzzzzz, do not use SMS speak when posting.

  • How to capture Runtime.exec() output? doesn't seem to work?

    This is the first time I've used Runtime.exec();
    Here's the code:
    Runtime rt = Runtime.getRuntime();
                process = rt.exec(jobCommand);
                BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line=null;
                while((line=input.readLine()) != null) {
                     System.out.println("OUTPUT: " + line);
                int exitVal = process.waitFor();
            } catch(Exception e) {
                 e.printStackTrace();
            }//end catchas you can see, this is just copied and pasted out of the standard example for this method.
    When it gets to the line:
    while((line=input.readLine()) != null)
    it doesn't read anything. However, when i run the SAME exact command from the windows CMD prompt i get a ton of output.
    what am i doing wrong here?
    thanks.

    Welcome to the forum!
    >
    as you can see, this is just copied and pasted out of the standard example for this method.
    >
    No one can see that - you didn't post a link to the example you said you copied.
    >
    it doesn't read anything. However, when i run the SAME exact command from the windows CMD prompt i get a ton of output.
    >
    No one can see what command you are talking about; you didn't post the commnd or even describe what output you expect to get.
    >
    what am i doing wrong here?
    >
    What you are doing wrong is not providing the code you are using, the command you are using or enough information about what exactly you are doing.
    No one can try to reproduce your problem based on what you posted.

  • Parsing java command line output to a gui

    Dear All,
    I am trying to implement a search engine for a project, i have a java file called Searcher.java, which searches for a particular text or sentence and gives the output based on the number of hits on a particular document, the document with the max hits is displayed first and so on,all the documents are are stored in a text file, I am trying to create a GUI for this file, the gui would consist of a text box,submit button,a list and a text area , when a user enters the text to search all the entries are displayed in the list box and upon clicking the individual item in the list the description should open up in the text area.
    The problem i am encountering is that i am not able to parse the output of the searcher.java file onto the GUI, i have no clue as to how to implement it , i would really appreciate it if anyone could help me out.
    the code for Searcher.java is as follows
    import java.util.*;
    public class Searcher {
    /** Specify the work directory !! */
    private static final String rootDir = "C:/HR/GUIAssign/";//on PC
    // private static final String rootDir = "/research/gm/Java/IR/"; // on Unix
    private static final String stopWordFile = "iStopWords.txt";
    private static final String docCollFile = "iDocColl.txt";
    private static final String invertedIndexFile = "ioInvertedIndex.txt";
    private StopWordSet stopWords = new StopWordSet(rootDir + stopWordFile);
    private Stemmer stemmer = new Stemmer();
    private TextTokenizer tok;
    private TextParser parser;
    private InvertedIndex inv;
    /** Creates a new instance of Searcher */
    public Searcher(TextTokenizer tok, TextParser parser) {
    this.tok = tok;
    this.parser = parser;
    ReaderWriter rw = new TextFileReaderWriter(rootDir);
    inv = rw.readInvertedIndex(invertedIndexFile);
    List search(String query) {
    System.out.println("\nSearching for <" + query + ">.");
    List hits = new ArrayList();
    int nbOfDocs = parser.getNbOfReadDocs();
    System.out.println("\nSearching for <" + query + "> among " + nbOfDocs +
    " documents.\n");
    double scores[] = new double[nbOfDocs]; // initial values 0.0
    String term;
    tok.setText(query);
    while(tok.hasMore()) {
    System.out.println("\nNext term: ");
    term = tok.nextToken();
    System.out.println(term);
    if(stopWords.contains(term))
    continue; // this terms can be ignored
    term = stemmer.stem(term); // apply the stemmer to get the root
    System.out.println("\n\nInfo on the term \"" + term + "\":");
    IndexTerm indexTerm = inv.getIndexTerm(term);
    if(indexTerm == null)
    System.out.print("Not in the vocabulary.");
    else {
    System.out.print("It appears " + indexTerm.getTermFreq() + " times, in "
    + indexTerm.getDocFreq() + " documents:\t");
    Iterator itr = indexTerm.getIterator();
    while(itr.hasNext()) {
    DocFreq docFreq = (DocFreq) itr.next();
    scores[docFreq.getDocId()] += docFreq.getFreq() /* / indexTerm.getDocFreq() */ ;
    // create hits from documents that have non-zero scores
    for(int i = 0; i < nbOfDocs; i++)
    if(scores[i] > 0.0)
    hits.add(new Hit(i, scores));
    // sort them in descending order of scores
    Collections.sort(hits, new Hit.CompareByScore());
    return hits;
    * @param args the command line arguments
    public static void main(String[] args) {
    TextTokenizer tok = TextTokenizer.getTokenizer("alpha");
    TextParser parser = new DummyParser(rootDir, tok);
    Searcher searcher = new Searcher(tok, parser);
    List hits = searcher.search("trade and board coffee, stock x is common");
    Iterator it = hits.iterator();
    while(it.hasNext()) {
    Hit hit = (Hit) it.next();
    int index = hit.getDocIndex();
    Doc doc = parser.getDoc(index);
    System.out.println("\n\nDoc " + index + " has a score of: " +
    hit.getScore() + "\n*** " + doc.getTitle() + " ***\n" +
    doc.getText());
    this code runs perfectly and gives the output on the command line
    the code for the GUI is as follows
    import java.awt.* ;
    import java.awt.event.* ;
    import javax.swing.* ;
    import javax.swing.event.*;
    public class HRSearch extends JFrame implements ActionListener {
    // keep references to all event sources
    private JLabel searchLabel;
    private JTextField searchField ;
    private JButton submitButton ;
    private JScrollPane searchScrollPane;
    private JTextArea textArea ;
    public HRSearch()
              Container contentPane = /*this.*/getContentPane( ) ;
              JPanel submitPanel = new JPanel();
              submitPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
              searchLabel = new JLabel("Search: ");
              searchLabel.setEnabled(false);
              submitPanel.add(searchLabel);
              searchField = new JTextField("", 20) ;
              searchField.setEditable(true) ;
              searchField.addActionListener(this) ;
              searchField.setEnabled(false);
              submitPanel.add(searchField) ;
              submitButton = new JButton("Submit") ;
              submitButton.addActionListener(this) ;
              submitButton.setEnabled(false);
              submitPanel.add(submitButton);
              contentPane.add(submitPanel, BorderLayout.NORTH);
    JPanel mainPanel = new JPanel() ;
                   mainPanel.setLayout(new FlowLayout(FlowLayout.LEFT)) ;
              JList searchList = new JList() ;
              // searchList.setEditable(false) ;
              searchList.setVisibleRowCount(20) ;
              searchScrollPane = new JScrollPane(searchList);
              mainPanel.add(searchScrollPane) ;
              textArea = new JTextArea("", 20, 40) ;
              textArea.setEditable(false) ;
              mainPanel.add(new JScrollPane(textArea) /*, BorderLayout.CENTER */) ;
              contentPane.add(mainPanel, BorderLayout.CENTER) ;
    public void actionPerformed(ActionEvent e) {
    String text ; // response to action event
    Object source = e.getSource( ) ;
    if (source != searchField && source != submitButton)
    return; // not interested in other actions
    // get text, trim leading and trailing spaces
    text = searchField.getText( ).trim() ;
    try {
    textArea.setText(textArea.getText() + "\n" + " " );
    catch(NumberFormatException exc) {
    JOptionPane.showMessageDialog(
    this, // address of "parent" or "anchor" frame
    "Not a number !", // the error message
    "Number Format Exception", // title of this modal dialogue
    JOptionPane.ERROR_MESSAGE // nature of this dialoge
    public static void main(String args[]) {
              final JFrame f = new HRSearch();
              // f.setBounds(100,100,500,450);
              f.pack();
              f.setVisible(true);
              f.setDefaultCloseOperation(EXIT_ON_CLOSE);
    i am stuck at this point and dont know what to do , please help me out.
    regards
    harsha

    I'm not positive I understand your problem... but let me recap what I think it is, then provide a solution:
    Your searched program can be run from the command line, and prints out (using system.out) the data you want. But NOW you want to create a GUI class, that intercepts that output, and displays it on the screen, and you can't because its going to the output stream and you're GUI isn't able to get it.
    If this is the case, what you can do is add two constructors to your Searcher class:
    public Searcher()
    this(System.out);
    public Searcher(OutputStream out)
    this.out = out;
    The idea being, that if you don't specify an output stream, the output goes to the console like normal. But if you do specify an output stream, the data gets fed back to you. So then in your GUI, you can do some binding of PipedInputStream and PipedOutputStream so when the Searcher class prints out, it comes right through the pipe into your GUI where you are waiting to read it.
    If this wasn't your problem, sorry :(
    Best,
    -Riyad

Maybe you are looking for

  • How to install Microsoft Office on MacBook Air?

    I just bought my first ever Apple MacBook and I am realy having hard time with it. Please someone tell me how to install the Microsoft Office 2011 on MacBook Air. Thank you so much!

  • Change teststand post actions from labview

    Hi, Is there a way to change the post action of a test in teststand from Labview. At the moment, if one of the tests fail out of limits then the post action is set to 'ON FAIL - GO TO NEXT STEP' but if the unit does not run then a diagnostics labview

  • Infoset on ODS and infoobject doesn't get data

    Hi Firends,   I have 4 fields in ODS (A,B,C,D) .  And an INFOBJECT 'X' compunded to 'A', 'B' . I am trying to create an infoset using this ODS with this infoobject 'X' & am joining  them as below: ODS-A =  INFOOBJECT-A ODS-B =  INFOOBJECT-B   But whe

  • How to find which screen/folder an app is in?

    I thought I read this a while ago but can't find it and can't remember...is there a way to find the "location" of an app? That is, I can use search to find an app to *launch* it. But what if I wanted to e.g. move it or delete it? It can be really har

  • How to unistall JDK 1.1.6???

    I have JDK 1.1.6 installed on my computer (running Windows 95) and now I'd like to uninstall this version of JDK, but when I opened the "Add/Remove Programs" dialog box (inside the "Control Panel" window) there wasn't any "JDK" stuff (or similar name