第八章 流 08_PrintIO

来源:互联网 发布:mac百度云怎么分享链接 编辑:程序博客网 时间:2024/05/01 18:41

鱼欲遇雨:每日都学习一点,持之以恒,天道酬勤!不能用电脑时,提前补上!(2012.9.2)


Print 流
1   PrintWriter和PrintStream都属于输出流,分别针对于字符和字节。
2   PrintWriter和PrintStream提供了重载的print方法
Println方法用于多种数据类型的输出
3   PrintWriter和PrintStream的输出操作不会抛出异常, 用户通过检测错误状态获取错误信息。
4   PrintWriter和PrintStream有自动flush功能。


PrintWriter( Writer out) 
PrintWriter(Writer out, boolean autoFlush)
PrintWriter(OutputStream out)
PrintWriter(OutputStream out, boolean autoFlush)
PrintWriter(OutputStream out)
PrintWriter(OutputStream out, boolean autoFlush)


示例代码:

// TestPrintStream1.javaimport java.io.*;public class TestPrintStream1 {public static void main(String args[]) {PrintStream ps = null;try{FileOutputStream fos = new FileOutputStream("c:/java/IO/log.txt");ps = new PrintStream(fos);}catch (IOException e) {e.printStackTrace();}if(ps != null) {System.setOut(ps);}int len = 0;for(char c = 0; c < 60000; c ++) {System.out.print(c + " ");if(len ++ >= 100){System.out.println();len = 0;}}}}

// TestPrintStream2.javaimport java.io.*;public class TestPrintStream1 {public static void main(String args[]) {PrintStream ps = null;try{FileOutputStream fos = new FileOutputStream("c:/java/IO/log.txt");ps = new PrintStream(fos);}catch (IOException e) {e.printStackTrace();}if(ps != null) {System.setOut(ps);}int len = 0;for(char c = 0; c < 60000; c ++) {System.out.print(c + " ");if(len ++ >= 100){System.out.println();len = 0;}}}}

// TestPrintStream3.javaimport java.util.*;import java.io.*;public class TestPrintStream3 {public static void main(String args[]) {String s = null;try{BufferedReader br = new BufferedReader (new InputStreamReader(System.in));FileWriter fw = new FileWriter("c:/java/IO/logfile.txt", true);PrintWriter pw = new PrintWriter(fw);while( (s = br.readLine()) != null) {if(s.equalsIgnoreCase("exit"))break;System.out.println(s.toUpperCase());pw.println("-----");pw.println(s.toUpperCase());pw.flush();}pw.println("===" + new Date() + "===");pw.flush();pw.close();}catch (IOException e){e.printStackTrace();}}}



原创粉丝点击