Java 处理流--打印流(PrintWriter和PrintStream)

在整个IO流中,打印流是输出信息最方便的类。

PrintStream和Printwriter:

public class PrintStream extends FilterOutputStream
public PrintStream(OutputStream out, boolean autoFlush)
public PrintWriter(OutputStream out, boolean autoFlush)

 System.out:

public final static PrintStream out = null;

要点:

1.提供了一系列重载的print和println方法,用于多种数据类型的输出。
2. PrintStream和PrintWriter的输出不会抛出异常。
3. PrintStream和PrintWriter有自动flush功能。
4. System.out返回的是PrintStream的实例。

import java.io.*;
/*
   在整个IO流中,打印流是输出信息最方便的类,
   打印流有PrintStream(字节打印流)和PrintWriter(字符打印流)两种。
 */
public class 打印流 {
    public static void main(String[] args) throws FileNotFoundException {
        new 字节打印流().print();
        new 字符打印流().print();
    }
}
class 字节打印流 {
    public void print() throws FileNotFoundException {
    //打印流System.out
        PrintStream ps =System.out;//由源码知System.out返回一个PrintSystem实例
        ps.println("输出");//打印流的输出不会抛出异常
        //PrintStream和PrintWriter有自动flush功能
        ps = new PrintStream(
                new BufferedOutputStream(
                        new FileOutputStream("bbb.txt")),true);
        ps.print("写出");
        //ps.flush();
        ps.close();

    //重定向输出端
        System.setOut(ps);
        System.out.println("输出变为写出");
        //重定向回控制台
        System.setOut(new PrintStream(
                new BufferedOutputStream(
                        new FileOutputStream(FileDescriptor.out)),true));
        System.out.println("back to 输出");
    }
}
class 字符打印流{
    public void print() throws FileNotFoundException {
        PrintWriter pw = new PrintWriter(
                new BufferedOutputStream(
                        new FileOutputStream("bbb.txt")), true);
        pw.print("写出");
        //pw.flush();
        pw.close();
    }
}


 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值