print流

PrintStream永远不会抛IOException

例子1代码:

import java.io.*;

public class TestPrintStream1 {
    public static void main(String[] args) {
        PrintStream ps = null;
        try {
            FileOutputStream fos = new FileOutputStream("D:/打码家族/java/mine/testIoStream/testPrintStream/log.txt");
            ps = new PrintStream(fos);
        } catch(IOException e) {
            e.printStackTrace();
        }
        if(ps!=null) {
            System.setOut(ps);//把System.out这根管,连到ps上。(管本来是连在黑窗口上的)
        }
        int ln = 0;
        for(int c = 0; c <= 60000 ; c++) {
            System.out.print((char)c+"   ");//因为这根管被接到了ps上,所以现在是print在log.bat里面。
            if(ln++>=100) {
                System.out.println();
                ln = 0;
            }
        }
    }
}

TestPrintStream2 代码:

import java.io.*;

public class TestPrintStream2 {
    public static void main(String[] args) {
        String fileName = args[0];//命令行参数,java testPrintStream2 fsdjf   那么args[0]就是fsdjf
        if(fileName!=null) {
            TestPrintStream2 tp2 = new TestPrintStream2();
            tp2.list(fileName,System.out);
        }
    }

    public void list(String fileName,PrintStream fs) {
        try {
            BufferedReader bfr = new BufferedReader(new FileReader(fileName));//FileReader节点流,字符流,插到文件上,外面加buffer,即加桶。
            String s = null;
            while( ( s=bfr.readLine() )!=null ) {
                fs.println(s);
            }
            bfr.close();
        } catch(IOException e) {
            e.printStackTrace();
            fs.println("无法读取文件");
        }
    }    

}

TestPrintStream3例子代码:

import java.util.*;
import java.io.*;

public class TestPrintStream3 {
    public static void main(String[] args) {
        String s = null;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));//一根管插到键盘上,外面套个stream变reader就是变字符流的,外面再套buffer就是桶
        try {
            FileWriter fw = new FileWriter("D:/打码家族/java/mine/testIoStream/testPrintStream/testPrintStream3/log.txt",true);//log4J  log for java的谐音,一个专门做日志的包
            PrintWriter log = new PrintWriter(fw);
            while( ( s=br.readLine() )!=null ) {
                if(s.equalsIgnoreCase("exit")) break;
                
                System.out.println(s.toUpperCase());
                log.println("-----");
                log.println(s.toUpperCase());
                log.flush();//printWriter虽然有自带flush但flush一次也没什么喔
            }
            log.println("==="+new Date()+"===");//Date这个类是专门处理时间的,一new这个类,就会自动记录当前时间,所以可以这样把它print出来
            log.flush();
            log.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}
原文地址:https://www.cnblogs.com/wangshen31/p/6809098.html