Java IO流--打印流

 

打印流主要功能是方便内容写至文件,打印流分为两种:

  (1)字节打印流:PrintStream

  (2)字符打印流:PrintWrite

 

代码示例:

package com.seven.javaSE;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Writer;

//打印流:字节打印流(PrintStream)、字符打印流(PrintWrite)
public class PrintStreamDemo {
    public static void main(String[] args) {
        printStream();
        printWrite();
    }
    
    public static void printStream() {
        try {
            OutputStream out = new FileOutputStream("C:/TestFile/target.txt");
            //加入缓冲
            BufferedOutputStream bos = new BufferedOutputStream(out);
            //加入字节打印流
            PrintStream ps = new PrintStream(bos);
            //相对比字节流,省去了将内容转化成字节数组的步骤
            ps.print("使用字节打印流,简便了向文件写入内容");
            ps.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        
    }
    
    public static void printWrite() {
        try {
            Writer write = new FileWriter("C://TestFile/source.txt");
            //加入缓冲
            BufferedWriter bw = new BufferedWriter(write);
            //加入字符打印流
            PrintWriter pw = new PrintWriter(bw);
            pw.print("使用字符打印流,加强文件写入");
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        
    }
    
    
}

 

posted @ 2022-06-17 17:47  藤原豆腐渣渣  阅读(79)  评论(0编辑  收藏  举报