系统提供的两个打印流:
PrintStream:字节打印流
PrintWriter:字符打印流
打印流应用的是装饰设计模式(基于抽象类的设计模式):核心依然是某个类(OutputStream) 的功能write(()) 但是为了得到更好的操作效果,让其支持的功能更多。
class PrintUtil{
private OutputStream out;
public PrintUtil(OutputStream out){
this.out = out;
}
public void print(String str){
try {
//核心在于OutputStream提供的write
this.out.write(str.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
public void println(String str){
this.print(str+"\r\n");
}
public void print(int num){
this.print(String.valueOf(num));
}
public void println(int num){
this.print(num+"\r\n");
}
public void print(double data){
this.print(String.valueOf(data));
}
public void println(double data){
this.print(data+"\r\n");
}
public void close(){
try {
this.out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Test {
public static void main(String[] args) throws FileNotFoundException {
//1.取得File对象
File file = new File("C:\\Users\\Lenovo\\Desktop\\Test.txt");
//2.取得输入流
PrintUtil printUtil = new PrintUtil(new FileOutputStream(file));
//3.进行数据输出
printUtil.print(10.0000);
printUtil.println(10);
printUtil.print("hello");
//4.关闭流
printUtil.close();
}
}
优点: 扩展功能特别方便,需要不同功能时只需要更换装饰类即可。
缺点: 类结构复杂。