Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Redirecting System.out to a variable.

  • 02-01-2006 04:31PM
    #1
    Registered Users, Registered Users 2 Posts: 21,264 ✭✭✭✭


    Ok I know how to redirect System.out to a file.
    FileOutputStream fos = null;;
    try {
       fos = new FileOutputStream("c:\\myTest.txt");
    } catch (FileNotFoundException e) {
       e.printStackTrace();
    }
    PrintStream out = new PrintStream(fos);
    System.setOut(out);
    


    I am curious how do you set it so that System.out will write to String or Stringbuffer?


Comments

  • Closed Accounts Posts: 17,208 ✭✭✭✭aidan_walsh


    You'll need to create a custom version of the String or Stringbuffer classes that extend PrintStream.


  • Registered Users, Registered Users 2 Posts: 21,264 ✭✭✭✭Hobbes


    Nevermind finally figured it out.
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    System.setOut(new PrintStream(byteStream, true));
    
    System.out.println("Hello World"); 
    
    String capturedText = byteStream.toString();
    

    Now I just have to figure out how to reset the System.out back to the way it was. :/

    [edit]

    Woot.. found that too. Thanks everyone. :)
    // Resets System.out back to the way it was.
    		System.setOut(
    				new PrintStream(
    				new BufferedOutputStream(
    				new FileOutputStream(
    				java.io.FileDescriptor.out), 128), true));
    


Advertisement