Java IO 打印流

PrintStream 类     其构造方法,  方法参数  可接收File类型, 接收 字符串类型 文件名, 接收 字节输出流 OutputStream

PrintWriter 类   其构造方法,  方法参数  可接收File类型, 接收字符串类型 文件名, 接收 字节输出流 OutputStream, 接收 字符输出流 Writer

综上 ,  PrintWriter >= PrintStream 

因此 实际使用  只用 PrintWriter     

//构造1
PrintWriter pw = new PrintWriter("c:\\1.txt");

//构造2
File file = new File("c:\\2.txt");
PrintWriter pw = new PrintWriter(file);


//构造3
FileOutputStream fos = new FileOutputStream("c:\\3.txt");
PrintWriter pw = new PrintWriter(fos);

//构造4
FileWriter fw = new FileWriter("c:\\4.txt");
PrintWriter pw = new PrintWriter(fw);

//构造5
FileOutputStream fos = new FileOutputStream("c:\\5.txt");
PrintWriter pw = new PrintWriter(fos,true);// 自动刷新的启动开关

 

注意:  自动刷新开关生效 的前提   写数据的目的地 必须是流对象 例如fos

 

 

PrintWriter 类  写 方法

write() 方法  与 flush()方法 密切结合   该方法写入文件前 需查码表对应     (100被写入后 write(100)   文件中 是小写字母d)

 

println() 方法    // 若自动刷新开关 开启 则无需  写flush()方法         该方法 能够保证原样输出   (100被写入后 print(100)   文件中就是100)

printf()  // 若自动刷新开关 开启 则无需  写flush()方法

format()  // 若自动刷新开关 开启 则无需  写flush()方法

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class TestIO {

    public static void main(String[] args)throws IOException {
        function1();
        function2();
    }
    
    public static void function1() throws FileNotFoundException{
        File file = new File("d:\\1.txt");
        PrintWriter pw = new PrintWriter(file);    //永远不会抛出IOException  但可以抛出其它异常    例如FileNotFoundException
        pw.write(100);
        pw.flush();
        pw.close();
    }
    
    public static void function2() throws IOException{
        File file = new File("d:\\2.txt");
        FileWriter fw = new FileWriter(file);//抛出IOException
        PrintWriter pw = new PrintWriter(fw, true);    //永远不会抛出IOException  但可以抛出其它异常
        pw.println(100);
        pw.println("hello world");
        pw.close();
    }

}

 

 

 

/*
 * 打印流实现文本复制
 *   读取数据源  BufferedReader+File 读取文本行
 *   写入数据目的 PrintWriter+println 自动刷新
 */


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;


public class PrintWriterDemo1 { public static void main(String[] args) throws IOException{ BufferedReader bfr = new BufferedReader(new FileReader("c:\\a.txt")); PrintWriter pw = new PrintWriter(new FileWriter("d:\\a.txt"),true); String line = null; while((line = bfr.readLine())!=null){ pw.println(line); } pw.close(); bfr.close(); } }

 

posted @ 2020-05-27 18:26  CherryYang  阅读(185)  评论(0编辑  收藏  举报