Redirecting System.out() output to a JTextArea control

I want to be able to redirect System.out() and System.err() messages to a JTextArea control:
I know how to redirect output to a file as follows:
FileOutputStream fos =
new FileOutputStream(filename, true);
PrintStream ps = new PrintStream(fos, true);
System.setOut(ps);
System.setErr(ps);
How can I set it up so that I can recognise when messages have been to System.out() with a view to displaying the message within the JTextArea?
I guess I need to set it up so that the JTextArea control acts as an Observer. The bit I'm having difficulty with is figuring out how I can automatically determine when information has been written to System.out()?
Hopefully I'm explaining my issue in enough detail and clarity.
thanks
- Garry

I would suggest you set up a separate thread to monitor System.out. Use a PipedOutputStream and redirect System.out to that, then connect that to a PipedInputStream that your other thread is continually waiting to read. Each time that thread reads a line, it should append the line to the JTextArea, using SwingUtilities.invokeLater.
This is just a rough outline of something that might work. Hope it helps.

Similar Messages

  • Redirecting System.out to a JTextArea

    How can I redirect the System.out Stream into a JTextArea?
    I found the method System.setOut(PrintStream out) but I don't know
    how to get the PrintStream of my TextArea.

    I don't know if this is the most efficient way but it provides an example of using Pipes:
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TextAreaStream extends JTextArea implements Runnable{
         private static final PipedOutputStream _pipeOut = new PipedOutputStream();
         static{
                   System.setOut( new PrintStream(_pipeOut) );
         private InputStream _pipeIn;
    private byte[] buffer = new byte[256];
         public TextAreaStream(){
              this(1,10);
         public TextAreaStream(int numRows, int numCols){
              super(numRows, numCols);
              Thread t = new Thread(this);
              t.setDaemon(true);
              t.start();
              try{
              pipeIn =  new BufferedInputStream(new PipedInputStream(pipeOut));
              catch(IOException e){
                   System.err.println("Error creating pipe: "+e);
         public void run(){
              while(true){
                   try{
                        //blocks at read
                        int bytesRead = _pipeIn.read(buffer);
                        append(new String(buffer,0,bytesRead));
                   catch(IOException e){
                        System.err.println(e);
         public static void main(String[] args){
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JTextArea text = new TextAreaStream();
              text.setBorder(BorderFactory.createTitledBorder("System.out"));
              f.getContentPane().add(text);
              //Add an input component
              JPanel north = new JPanel(new FlowLayout(FlowLayout.LEFT));
              final JTextField field = new JTextField(25);
              north.add(field);
              north.add(new JLabel("Add text, press Enter"));
              f.getContentPane().add(north, BorderLayout.NORTH);
              field.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        System.out.println(field.getText());
                        field.setText("");
    f.setSize(600, 400);
              f.show();
    }

  • Redirect, System.out  ?

    Hi.
    I want to redirect System.out to a Swing Component like JTextArea, etc.
    try with printstream, Reader, etc. but i dont know how.!.
    I want to see, messages (The standard out) in a Swing Component.
    plis some help..
    tnks.

    I was using the Redirect method you made edna for my software and it works wonderfully when using strings, unfortunately I ran in to a strange problem which is fitting since my current objective is very strange.
    I am writing a piece of software that has an embedded jython interpreter in it. When I execute my jython scripts all the output went to the console and I had no direct way of saying append to this particular text area since I wasn't able to pass my Java GUI class in to the script.
    Thus redirecting my output with your method came in quite handy. This is where the problem comes in. I tried the println function in my regular java classes and all the primitive types worked fine, but within in the script only String worked. Here is the code for the println function
    PrintStream stdout = new PrintStream(System.out) {
       public void println(String x) {
          outputTextArea.append(x + "\n");
       public void println(int x) {
          outputTextArea.append(x + "\n");
       public void println(boolean x) {
          outputTextArea.append(x + "\n");
       public void println(Object x) {
          outputTextArea.append(x.toString() + '\n');
    };Here is the sample Jython code:
    import JythonScripter
    System.out.println(4) #fails to print correctly
    System.out.println("HelloWorld") #works
    System.out.println(10) #fails
    System.out.println("Goodbye Cruel World") #works
    If you have any advice on why strings would work but not other types I would greatly appreciate it.

  • Redirecting System.out to a textfield

    I want the output created by System.out (especially error messages) redirected to a textfield in stead of the console. How can I do this?

    this is how I've done it. Just create a new instance of this class and pass in your TextArea. It redirects System.out and checks for messages on System.out every 5 seconds.
    import java.io.*;
    import javax.swing.*;
    public class TextOut
    implements Runnable
         private JTextArea text;
         private Reader in;
         private Thread t;
         public TextOut( JTextArea text )
              throws Exception
              this.text = text;
              PipedOutputStream pout = new PipedOutputStream();
              System.setOut( new PrintStream( pout ) );
              in = new InputStreamReader( new PipedInputStream( pout ) );
              t = new Thread( this );
              t.start();
         public void run()
              while( true )
                   try
                        StringBuffer buffer = null;
                        while( in.ready() )
                             if ( buffer == null ) buffer = new StringBuffer();
                             buffer.append( (char)in.read() );
                        if ( buffer != null )
                             text.append( buffer.toString() );
                             java.awt.Rectangle r = new java.awt.Rectangle();
                             text.computeVisibleRect( r );
                             text.repaint( r );
                        t.sleep( 5000 );
                   } catch (IOException ioe) {
                        text.append( "" + ioe );
                   } catch (InterruptedException ie ) {
                        text.append( "" + ie );

  • Redirecting System.out?

    I am working with a team, and I am testing a standalone Java application using separate unit tests. The program takes text input and outputs some text results, but the way it is set up, it will output directly to System.out as soon as it needs it. I am not in control of the way it outputs the results.
    I need to capture all of the results from System.out, and compare them to what I know should be printed out. How do I do this without touching the original source files? Is there a way to do it purely in Java (my backup is to use shell scripts, but I really don't want to)?

    Well, you don't need to change all the source files, but you will need to
    change the source file with your main method.You don't even have to do that: build a Wrapper class with its own main
    that redirects System.out to a file and calls the Application.main afterwards.
    Instead of starting the Application, start the Wrapper.
    kind regards,
    Jos

  • How do I redirect System.err output in iPlanet 4.1?

    All,
    I've been trying for days to redirect System.err output from a Java program
    to a log file. I followed the instructions here:
    http://knowledgebase.iplanet.com/ikb/kb/articles/4790.html
    Unfortunately, nothing has been written to any of the log files (even though
    I have plenty of System.err.println()'s in my code).
    Anyone else get this to work correctly?
    Thanks in advance,
    --Bill                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Hi,
    What is the product web server or application server ? If it is application
    server then I'm very sure that this output will be seen in the kjs log file in
    Unix and in the command window in Windows NT/2K, only if you have allowed the
    process to interact with desktop. Please let me know if this answers your
    question for me to help you further on this.
    Regards
    Raj
    "news.uswest.net" wrote:
    All,
    I've been trying for days to redirect System.err output from a Java program
    to a log file. I followed the instructions here:
    http://knowledgebase.iplanet.com/ikb/kb/articles/4790.html
    Unfortunately, nothing has been written to any of the log files (even though
    I have plenty of System.err.println()'s in my code).
    Anyone else get this to work correctly?
    Thanks in advance,
    --Bill                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Redirect system.out.println() to a file

    hi all,
         how can i redirect all the console prints to a txt file in java application? i have used system.out oftenly in many class throught the
    application. is there any way to redirect all those console prints to a
    txt file by converting or assigning the System.out stream to a stream for filewriter or
    somthing like that, so that whenever system.out.println() is executed
    the content is written to a file insted of on the console.
    thanks in advance
    Sojan

    Actually,System.setOut(new PrintStream(new FileOutputStream("output.txt"), true));
    System.setErr(System.out);since setOut wants a PrintStream and not just some OuputStream...

  • Redirecting System.out/err

    Hi all,
    Is there an easy way to redirect the System.out/err stream to my own stream? I want to implement that everything going to System.out/err will be printed in a JTextArea instead of the console (Like JBuilder does for example).
    Thanks for any hint, Mathias

    System.setErr(myErrorOutputStream);
    System.setOut(myStdOutStream);

  • Redirecting System.out and System.err to files

    Is there a way I can configure my web-appliction (in web.xml or something) to redirect all the output (.err and .out) to specific files?

    I think you could create PrinStreamS from your desired output files and then use System.setOut(<...>) and System.setErr(<...>). Place this code in a servlet that you load at startup...

  • Redirecting system.out to a file

    I want to have the output of these threads go to a file, which it is doing now, but the program is finishing before all the data is written to the file.
    I had another idea that the threads could write to a shared stringbuffer and then when they have finished, i could write the contents of that stringbuffer to a file, but when do it tell it to write to the file. how can i tell when the threads are finished.
    /*      12 Nov 2002
         Class extends PThread which extends Thread.
    import Concurrency.*;
    import java.io.*; //added to write output to a file
    public class Exercise1 extends PThread{
         private static File theOutputFile;
         private static FileWriter fileWriterStream;
         private static int counter = 0;
         public Exercise1() {
              try {
                   if(theOutputFile == null) {
                        theOutputFile = new File("output.txt");
                        fileWriterStream = new FileWriter(theOutputFile);
              }catch(IOException ioe){}     
         public static void main(String[] args) throws IOException {
              System.out.println("Dave Casserly\n" +
                                       "Check the source folder for a file called output.txt\n" +
                                       "This contains the programs output.\n");
              Exercise1 thread1 = new Exercise1();
              Exercise1 thread2 = new Exercise1();
              thread1.start();
              thread2.start();
         //each thread will look at counter make sure its less than 1000,
         //get the current counter value and increment it
         //print it to screen
         //then increment the static counter
         public void run(){
              try {
                   while(counter <= 1000) {
                        int count = counter;
                        count++;
                        counter++;
                        System.out.println("COUNT = " + count);                    //write to screen
                        fileWriterStream.write("COUNT = " + count + "\n");      //write to file
                        counter = count;     
              }catch(IOException io){}     
    }//end of class

    You need to join the main thread with the child threads.
    Something like this:
      Exercise1 thread1 = new Exercise1();
      Exercise1 thread2 = new Exercise1();
      thread1.start();
      thread2.start();
      thread2.join();
      thread1.join();Or something.

  • Where can I see System.out output?

    This question has been posted back in may and if somebody found out what the correct answer is please let me know.
    Thank you.
    Hi All
    How can I see the results of my System.out.prints?
    Marcnull

    I'm not sure if this is what you're looking for, but when Java code is run inside 8i, the System.out can be found in the 'udump' directory on your server. I believe there is a file there for each session -- look for the last updated. Maybe someone who knows more about 8i can say exactly what the 'udump' directory is...
    If you're running Java published as PL/SQL in SQL*Plus, you can redirect the System.out to your SQL*Plus session like this:
    SET SERVEROUTPUT ON SIZE 5000
    CALL DBMS_JAVA.SET_OUTPUT(5000);
    (The size can be from 2,000-1,000,000)
    I've run some Java in 8i by itself, but I'm still trying to understand architecturally where the "border" between 9iAS and 8i is...

  • Is it possible to redirect System.out and System.in for a thread

    I would like to run two threads. One should keep writing to System.out and System.in. The other thread output written to System.out and System.in shoudl be captured and written to a file. Is this possible? I don't think so, but perhaps someone know some workaround.
    rasped

    hmmm sure it's possible. You can write an outputstream that does different things depending on which thread is running, and then set system.out to a printstream that writes to that outputstream.

  • Urgent: Redirecting System.out.println to more than one place

    Hi All,
    I want to divert all my System.out.println() statements to a Log file as well as on to the screen.
    But only one of the 2 options actually works.
    So if anyone can suggest me some ways I will appreciate very much.
    My code looks something like this:-
    if (m_filename != null) {
    try {
    FileOutputStream fos = new FileOutputStream(m_filename);
    PrintStream ps = new PrintStream(fos);
    System.setOut(ps);
    System.setErr(ps);
    //This code Added for Printing Onto Screen But it does not work
    Stream ps1 = new PrintStream(System.out);
    System.setOut(ps1);
    System.setErr(ps1);
    } catch (IOException ioe) {
    System.out.println("Could not create log file " + m_filename + " because " + ioe);
    As far as logging onto file is menat it works when i set it but printing onto screen does not.
    How can i achive it
    Thanks
    Raj

    Hi,
    You are right but in my current scenario i cannot incorporate this log4j because my application is using some other framework and I am just trying to override this frameworks loggig behaviour so that it logs to both a log file as well as on to the screen.
    Here is the code that this framework uses for logging and i am simply overriding it to do the reqd thing but its not working for me:-
    * Resets the System's out and err OutputStreams to the Launcher's
    * own ThreadedOutputStream, so that output from different threads
    * can be tracked efficiently.
    protected void setOutputStreams() {
         if (scInfo.size() <= 1) {
    // don't need Threaded handling with one thread
    if (m_filename != null) {
    try {
    FileOutputStream fos = new FileOutputStream(m_filename);
    PrintStream ps = new PrintStream(fos);
    System.setOut(ps);
    System.setErr(ps);
    //Added for Printing Onto Screen
                             PrintStream ps1 = new PrintStream(System.out);
    System.setOut(ps1);
    System.setErr(ps1);
    } catch (IOException ioe) {
    Debug.fatalError("Launcher.setOutputStreams","Could not create log file " + m_filename + " because " + ioe);
    else {
    Debug.information("Launcher.setOutputStreams","Initializing ThreadedPrintStream");
    if (m_filename == null) {
    System.setOut(new ThreadedPrintStream(System.out));
    System.setErr(new ThreadedPrintStream(System.err));
    else {
    PrintStream out = new ThreadedPrintStream(m_filename);
    System.setOut(out);
    System.setErr(out);
    //Added for Printing Onto Screen
    System.setOut(new ThreadedPrintStream(System.out));
    System.setErr(new ThreadedPrintStream(System.err));
    Debug.information("Launcher.setOutputStreams","ThreadedPrintStream initialized.");
    Thanks
    Raj

  • Where does System.out output go?!!!

    Hi,
    I was wondering where does the output for System.out and such goes to? To which log file in OAS? I couldn't seems to be able to locate the log file storing this information.
    Any comment will be a great help to me, thxs in advance!
    Jason

    zhicheng,
    Regarding you second question ....
    2. Windows Services
    After installation, there are six windows services
    created: XXXAgent, XXXEMWebsite, XXXProcessManager,
    What doesn the above three means? I have tried to
    stop them manually(is there any order to follow?),
    but many times the XXXEMWebsite service failed to
    stop successfully, then I have to restart my
    computer. What's the matter? XXXEMWebsite is the service for starting/stopping the Enterprise Manager of iAS. This represents the file emctl.bat on your file system.
    XXXProcessManager is the file opmn.bat on your file system. This is used for starting/stopping all your iAS Processes.
    I have stopped all the services of iAS on windows several times without facing any problems. Just one word here, I always used to stop the ProcessManager service at the start and EMWebsite service at the last.
    Try if this helps you too.
    Regards.

  • To redirect System.out stream output on swing's JTextArea

    Following is a program that needs to print output as follows:-
    EXPECTED OUTPUT ON GUI:_ In action block (datapayload value) In Routing block (argus value)
    PRESENT PROGRAM OUTPUT ON GUI_ In action block (datapayload value)
    please examine the below code and correct mistakes to get the expected output as given above.....
    I am not getting the second line as output on GUI i.e., In Routing block (argus value)
        import java.awt.*;
        import javax.swing.*;
        import java.awt.event.*;
        import java.io.*;
        public class Demo extends JFrame implements ActionListener
          JTextField datapayload;
          JLabel Datapayload;
          JButton submit;
          JTextArea textFieldName;
          public Demo()
             DemoLayout customLayout = new DemoLayout();     
             getContentPane().setFont(new Font("Helvetica", Font.PLAIN, 12));
             getContentPane().setLayout(customLayout);
             Datapayload = new JLabel("Enter DataPayload:");
             getContentPane().add(Datapayload);
             datapayload = new JTextField("abcd...");
             getContentPane().add(datapayload);
             submit = new JButton("submit");
             getContentPane().add(submit);
             textFieldName = new JTextArea(80,10);
             textFieldName.setEditable( false );
             JScrollPane scroll = new JScrollPane(textFieldName) ;
             scroll.setBounds( 10, 60, 225, 150 );
             getContentPane().add( scroll );
             submit.addActionListener(this);
             setSize(getPreferredSize());
           public void actionPerformed(ActionEvent e)
              String demodata=datapayload.getText();
                 textFieldName.append("In Action Block"+"\t"+demodata);  
              Demo pr = new Demo();                              
              pr.DemoRoute(demodata);
           public void DemoRoute(String argus)
                 textFieldName.append("In routing block"+"\t"+argus);
            public static void main(String args[])
                 Demo window = new Demo();
                 window.setTitle("Demo");
                 window.pack();
                 window.show();
        class DemoLayout implements LayoutManager
           public DemoLayout() {  }
           public void addLayoutComponent(String name, Component comp) {   }
           public void removeLayoutComponent(Component comp) {  }
           public Dimension preferredLayoutSize(Container parent)
             Dimension dim = new Dimension(0, 0);
             Insets insets = parent.getInsets();
             dim.width = 320 + insets.left + insets.right;
             dim.height = 240 + insets.top + insets.bottom;
             return dim;
           public Dimension minimumLayoutSize(Container parent)
             Dimension dim = new Dimension(0, 0);
             return dim;
           public void layoutContainer(Container parent)
             Insets insets = parent.getInsets();
             Component c;
             c = parent.getComponent(0);
             if (c.isVisible()) {c.setBounds(insets.left+90,insets.top+8,172,26);}
             c = parent.getComponent(1);
             if (c.isVisible()) {c.setBounds(insets.left+230,insets.top+8,172,26);}
             c = parent.getComponent(2);
             if (c.isVisible()) {c.setBounds(insets.left+230,insets.top+52,142,26);}
             c = parent.getComponent(3);
             if (c.isVisible()) {c.setBounds(insets.left+90,insets.top+100,472,268);}
        }  Edited by: 997189 on Mar 31, 2013 8:52 AM

    Hi,
    change your actionPerformed() method as below to get the required output.
    public void actionPerformed(ActionEvent e)
              String demodata=datapayload.getText();
                 textFieldName.append("In Action Block"+"\t"+demodata);  
              //Demo pr = new Demo();      You are creating a new object to all DemoRoute method. This is the problem                         
              //pr.DemoRoute(demodata);
                 this.DemoRoute(demodata);
    }And also my suggestion is follow java coding conventions while coding

Maybe you are looking for

  • Help!  iPad Mail replying with account name

    Greetings, I couldn't find a topic about this so I am starting a thread here.  It's just a quick question: I have all of my email accounts set up on my iPad, for example, "My Yahoo" but when I reply or forward emails from the account on the iPad, peo

  • How much information is Diagnostics and usage supposed to capture?

    I think that the log has too much information in it. It list in plain text what apps I've downloaded that day , how many times I've accessed my camera from the lock screen, the number of times I've entered my pass code correct and not. There's lots m

  • Can I make 2 libraries, internal and external?

    I currently have an iTunes library which is taking up too much room on my internal hard drive. I have planned on moving the library to an external HD. The problem is that I am about to hit the road for some touring with a band and would love to have

  • Paid for and downloaded all the new games for new gen ipod

    I purchased all the new games and they appeared in my main apple page. After turning computer off and on again the games were gone. I attemeped to download again but was told by apple that I had already downloaded them and would have to pay again if

  • Satellite A200-TH7 - Windows Explorer is not responding

    On random occasions (normally when I wake up the PC), and I click the volume control in the taskbar, nothing will pop up. Then I'll go to move the physical volume control slider and nothing will happen. However, at that point, I'll try to click anywh