装饰类:
package the_mass.decorator; import java.io.*; public class LogOutputStream extends OutputStream { private OutputStream os; public LogOutputStream(OutputStream outputStream) { this.os = outputStream; } @Override public void write(int b) throws IOException { this.os.write(b); } @Override public void write(byte[] b) throws IOException { System.out.println("开始了"); super.write(b); System.out.println("结束了"); } }
充当进度条:
package the_mass.decorator; import java.io.IOException; import java.io.OutputStream; public class ProgressOutStream extends OutputStream { private OutputStream os; public ProgressOutStream(OutputStream outputStream) { this.os=outputStream; } @Override public void write(int b) throws IOException { this.os.write(b); } @Override public void write(byte[] b) throws IOException { System.out.println(">>>>>>>>>>>>>"); super.write(b); } }
测试:
package the_mass.decorator; import java.io.FileOutputStream; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { FileOutputStream outputStream =new FileOutputStream("e:/aaa"); LogOutputStream los = new LogOutputStream(outputStream); ProgressOutStream pos = new ProgressOutStream(outputStream); los.write("welcome".getBytes()); //使用指定的字符集将字符串编码为 byte 序列,并将结果存储到一个新的 byte 数组中。 pos.write("Hello wrold".getBytes()); } }