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.

Similar Messages

  • 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

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

  • 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 );

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

  • System.out/err log file redirection

    Hi,
    Do u know if System.out/err are redirected in
    a log file with Oracle 9ias 9.0.4 (Production Release) ?
    If yes, which one ?
    Thanks

    You may be looking for the stdout/stderr process output.
    Almost all components in Oracle Application Server 10g
    (9.0.4) are managed (at the process level) by OPMN. To
    preserve the stdout and stderr of every process, all
    processes started by OPMN have their stdout/stderr
    redirected to a file (one file for each running process).
    This file is sometimes referred to as the "console log".
    Console logs are located in $OH/opmn/logs and have a
    filenames containing '~' chars. Identifying which
    console log file is associated with which process
    should be intuitive.
    When a process terminates and is replaced by a new
    process, console log output from the previous process is
    preserved and the replacement process appends to the
    end of the console log file.

  • URGENT : System.out AND OACorexx files! log files more than 4Giga

    Hi all,
    I have a client with a custom done in OAF where there are a lot of System.out... and System.err "logs" print.
    The problem is that these logs are written in OACorexxx files under Apache/Jserv/logs/jvm directory: in only 4 days more than 4G size!
    Is possible to disable this logs?
    Thanks,
    Carlo

    Calling java.lang.System.setOut(PrintStream out) will allow you to redirect the System.out calls. You can direct them to null.
    --Shiv                                                                                                                                                                                                                                                                               

  • 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();
    }

  • 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);

  • 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

  • Java Beans System.out.println Log file

    Helllo,
    I have Forms 11.1.2 installed on linux. I developed a java bean and put some System.out.println() statements. The bean itself is working but where do i look for the debug statement logs that i am generating via System.out.println() statements.
    Please let me know if you need more information, I will post asap.
    thanks in advance,
    Prasad.

    Prabodh,
    thanks, added the following line to the implementation class in java bean:
    private final static Logger logger = Logger.getLogger(MyBean.class.getName());
    and then in the init() method, i put
    logger.info("Prasad .... in init);
    Does this automatically goes into weblogic managed server WLS_FORMS (in my case) standard out?
    Or do i need to do anything else, i know weblogic comes up with its own diagnostic logging and is famous for supressing other loggers.... just want to run this by you as well.
    thanks,
    Prasad,

  • Redirecting System.out stream to a TextArea

    I hope this isn't a stupid question--I'm blanking pretty hard.
    I want to use System.setOut() to direct standard output to a TextArea within a Frame. Is there a way to setup a TextArea to receive text from an output stream, or is an intermediary of some sort necessary?
    I feel like this is pretty easy, but I'm stumbling. That's what I get for doing J2EE for a year rather than GUI. :P
    Any input is appreciated!

    Here's the compiled and tested code...I learned some good stuff from this link as to why my simpler approach didn't work:
    http://www.devx.com/upload/registered/features/javapro/1999/11nov99/tl1199/tl1199.asp
    Here is my code:
      class OutRouter implements Runnable
        PipedInputStream pipeIn = null;
        JTextArea textArea = null;
        OutRouter( JTextArea ta, PipedOutputStream pos)
          try
            pipeIn = new PipedInputStream(pos);
          catch(IOException ioe)
            ioe.printStackTrace(System.err);
            System.exit(1);
          textArea = ta;
        public void run()
          String line = null;
          BufferedReader pipeReader = new BufferedReader(
            new InputStreamReader(pipeIn));
          try
            while(true)
              Thread.sleep(100);
              if(pipeIn.available() == 0)
                continue;
              line = pipeReader.readLine();
              if(line == null)
                continue;
              System.err.println("Line = " + line);
              final String fLine = line;
              SwingUtilities.invokeAndWait( new Runnable()
                {public void run()
                  { textArea.append(fLine + "\n"); }
          catch(InvocationTargetException ite)
          { ite.printStackTrace(System.err); System.exit(1); }
          catch(InterruptedException ie)
          { ie.printStackTrace(System.err); System.exit(1); }
          catch(IOException ioe)
          { ioe.printStackTrace(System.err); System.exit(1); }
      }

Maybe you are looking for

  • Error while running Java Web Start in JDK 1.5

    I have been running an application using Jboss3.2 in JDK1.4.2_09. The Java Web Start application ran perfectly then. Now, I am running Jboss3.2 with JDK 1.5.0_11. While some applications (HTML client and some Java Web Start applications are working c

  • PDF files will not open in a Safari (v 6.0.5) browser window

    PDF files will not open in a Safari (v 6.0.5) browser window, OS 10.8.5. Version 11.0.04 Adobe Reader and Plug-ins installed. Both local and internet files do not load. What is happening here?

  • Trace example in examples.jar

    Hello: The Trace example in examples.jar that comes with JDK 1.4 is very useful, but very slow. I was thinking how could the source code be modified so that I could use the same by connecting to a running JVM so that it doesn't log at startup. The ap

  • FI-GL Activating for Consolidation SEM BCS

    Hello together, can somebody tell me in a few steps how to activate the FI-GL (0FI_GL_6) that it can be used for consolidation in SEM BCS. My problem is that FI_GL_6 (and also FIGL_C10 for new FI-GL) have not all required fields for consolidation in

  • Include Java script in the abap webdynpro

    Dear expert, Anyone know how can i include a java script in the abap web dynpro. Thanks Regards, Bryan