Java-打印输出流

如果想输出字符串,可使用Writer直接输出,也可以使用OutputStream将字符串变为字节数组;如果输出数字,需要将数字变为字符串,在变为字节数组输出。

Q:实现一个输出功能类,加强的OutputStream和Writer

package com.joeaaa.file;

/*
* 定义一个输出功能类
*/

import java.io.*;

class PrintUtil{
    private OutputStream output = null;
    public PrintUtil(OutputStream output){
        this.output = output;
    }
    public void print(String str){
        try{
            this.output.write(str.getBytes());
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    public void println(String str){
        this.print(str.concat("\n"));
    }
    public void print(int num){
        this.print(String.valueOf(num));
    }
    public void println(int num){
        this.println(String.valueOf(num));
    }
    public void print(double num){
        this.print(String.valueOf(num));
    }
    public void println(double num){
        this.println(String.valueOf(num));
    }
    public void close(){
        try {
            this.output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
public class PrintUtilTest {
    public static void main(String[] args) throws FileNotFoundException {
        PrintUtil tools = new PrintUtil(new FileOutputStream(new File("/User/joe/desktop/test.txt")));
        tools.print("name: ");
        tools.println("Alex");
        tools.print(1);
        tools.print("+");
        tools.print(1);
        tools.println(1+1);
        tools.close();
    }
}