Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Redirecting System.out to a variable.

  • 02-01-2006 3: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