标签:
PrintWriter和PrintStream都属于输出流,分别针对字符和字节。
PrintWriter和PrintStream提供了重载的print,println方法用于多种类型的输出
PrintWriter和PrintStream的输出操作不会抛出异常,用户通过检测错误状态获取错误信息。
1 import java.io.File; 2 import java.io.FileNotFoundException; 3 import java.io.FileOutputStream; 4 import java.io.PrintStream; 5 6 7 public class TestPrintStream1 { 8 9 /** 10 * @param args 11 */ 12 public static void main(String[] args) { 13 // TODO Auto-generated method stub 14 PrintStream ps=null; 15 try { 16 FileOutputStream fos=new FileOutputStream("d:"+File.separator+"test.txt"); 17 ps=new PrintStream(fos); 18 } catch (FileNotFoundException e) { 19 e.printStackTrace(); 20 } 21 if(ps!=null){ 22 System.setOut(ps); 23 } 24 25 int l=0; 26 for(char c=0;c<=60000;c++){ 27 System.out.println(c); 28 } 29 } 30 31 }
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); 12 while ((s = br.readLine())!=null) { 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 }
标签:
原文地址:http://www.cnblogs.com/andong2015/p/4251117.html