/* * Copyright (c) 2001 Matthew Feldt. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided the copyright notice above is * retained. * * THIS SOFTWARE IS PROVIDED ''AS IS'' AND WITHOUT ANY EXPRESSED OR * IMPLIED WARRANTIES. */ /** * TeeOutputStream.java * * Java Examples In A Nutshell Copyright (c) 2000 David Flanagan * Exercise 3-7: * Write a subclass of OutputStream named TeeOutputStream that acts like a T * joint in a pipe; the stream sends its output to two different output streams, * specified when the TeeOutputStream is created. Write a simple test program * that uses two TeeOutputStream objects to send text read from System.in to * System.out and to two different test files. * * @author Matthew Feldt * @version 1.0, 02/12/2001 08:23 */ package com.feldt.examples.io; import java.io.*; public class TeeOutputStream extends OutputStream { OutputStream ostream1, ostream2; /** sole TeeOutputStream constructor */ TeeOutputStream(OutputStream o1, OutputStream o2) throws IOException { ostream1 = o1; ostream2 = o2; } public void close() throws IOException { ostream1.close(); ostream2.close(); } public void flush() throws IOException { ostream1.flush(); ostream2.flush(); } public void write(int b) throws IOException { byte[] buf = new byte[1]; buf[0] = (byte)b; write(buf, 0, 1); } public void write(byte[] b, int off, int len) throws IOException { ostream1.write(b, off, len); ostream2.write(b, off, len); } /** test class */ static class Test { public static void main (String args[]) { final String f1 = "tee1.out", f2 = "tee2.out"; int ch; try { // create a TeeOutputStream with System.out and a file // as output streams TeeOutputStream t1 = new TeeOutputStream( System.out, new FileOutputStream(f1)); // create a TeeOutputStream with t1 and a second file as // output streams TeeOutputStream tee = new TeeOutputStream( t1, new FileOutputStream(f2)); // read characters from System.in and write to the tee while ((ch = System.in.read()) != -1) { tee.write(ch); } tee.close(); // close the tee } catch(FileNotFoundException e) { System.err.println(e.getMessage()); } catch(IOException e) { System.err.println(e.getMessage()); } } } }