Print流
PrintWriter 和 PrintStream 都属于输出流,前者字符流,后者字节流。
二者都提供了重载了的print和println方法,用于多种类型数据的输出。
二者的输出操作不会抛出异常,用户通过检测错误状态获取错误信息。
二者均有自动flush功能。
构造方法:
PrintWriter(Writer out)
PrintWriter(Writer out , boolean autoFlush)
PrintWriter(OutputStream out)
PrintWriter(OutputStream out , boolean autoFlush)
PrintStream(OutputStream out)
PrintStream(OutputStream out , boolean autoFlush)
1: import java.io.*;
2: public class TestPrintStream1 {
3: public static void main(String[] args) {
4: PrintStream ps = null;
5: try {
6: FileOutputStream fos =
7: new FileOutputStream("d:\\bak\\log.dat");
8: ps = new PrintStream(fos);
9: } catch (IOException e) {
10: e.printStackTrace();
11: }
12: if(ps != null){
13: System.setOut(ps); //原本out指向DOS窗口,现在用setOut方法将输出指向ps,
//也就是d:\\bak\\log.dat这个文件了
14: }
15: int ln = 0;
16: for(char c = 0; c <= 60000; c++){
17: System.out.print(c+ " ");
18: if(ln++ >=100){ System.out.println(); ln = 0;}
19: }
20: }
21: }
1: import java.io.*;
2: public class TestPrintStream2 {
3: public static void main(String[] args) {
4:
String filename = args[0];
// 命令行参数
5: if(filename!=null){list(filename,System.out);}
6: }
7: public static void list(String f,PrintStream fs){
8: try {
9: BufferedReader br =
10: new BufferedReader(new FileReader(f));
11: String s = null;
12: while((s=br.readLine())!=null){
13: fs.println(s);
14: }
15: br.close();
16: } catch (IOException e) {
17: fs.println("无法读取文件");
18: }
19: }
20: }
1: import java.util.*;
2: import java.io.*;
3: public class TestPrintStream3 {
4: public static void main(String[] args) {
5: String s = null;
6: BufferedReader br = new BufferedReader(
7: new InputStreamReader(System.in
));
8: try {
9: FileWriter fw = new FileWriter
10: ("d:\\bak\\logfile.log", true); //将字符流写到日志
11: PrintWriter log = new PrintWriter(fw); //用PrintWriter包住FileWriter,
//因为FileWriter是Writer的子类
12: while ((s =br.readLine
())!=null) { //之所以要把InputStreamReader包到BufferedReader里
//就是要用readline()这个方法
13: if(s.equalsIgnoreCase("exit")) break;
14: System.out.println(s.toUpperCase());
15: log.println("-----");
16: log.println(s.toUpperCase());
17: log.flush();
18: }
19: log.println("==="+new Date()
+"===");
20: log.flush();
21: log.close();
22: } catch (IOException e) {
23: e.printStackTrace();
24: }
25: }
26: }