Java Basics - Print Stream of IO Stream Object (PrintStream and PrintWriter)
Author: Yin Zhengjie
Copyright statement: original works, please do not reprint! Otherwise held liable.
1. Characteristics of the print stream
There are two print objects, namely the byte print stream (PrintStream) and the character print routine (PrintWriter). The methods of the two print streams are exactly the same. The output destination of the print stream is specified in the construction method. The print stream has the following characteristics:
1>. This stream is not responsible for the data source, only the data purpose;
2>.Add functions for other output streams;
3>. IOException will never be thrown, other exceptions may be thrown;
2. The purpose of the print stream output is the File object
If you want the file to input some data as it is, then the print stream is very suitable for you! Let's look at the following cases:
1 /* 2 @author :yinzhengjie 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/ 4 EMAIL:[email protected] 5 */ 6 7 package cn.org.yinzhengjie.note6; 8 9 import java.io.File; 10 import java.io.FileNotFoundException; 11 import java.io.IOException; 12 import java.io.PrintWriter; 13 14 public class PrintWriterDemo { 15 public static void main(String[] args) throws IOException { 16 File file = new File("yinzhengjie.txt" ); 17 if (! file.exists()) { 18 file.createNewFile(); 19 } 20 // Create character output stream, encapsulate file 21 PrintWriter pw = new PrintWriter(file); 22 // Write int data type to file 23 pw.println(100 ); 24 // Write double data type to file 25 pw.println(3.14 ); 26 // Write to file Write boolean data type 27 in pw.println(true ); 28 // Release resources 29 pw.close(); 30 } 31 }
3. Print stream copy text file
1 /* 2 @author :yinzhengjie 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/ 4 EMAIL:[email protected] 5 */ 6 7 package cn.org.yinzhengjie.note6; 8 9 import java.io.BufferedReader; 10 import java.io.FileReader; 11 import java.io.FileWriter; 12 import java.io.IOException; 13 import java.io.PrintWriter; 14 15 public class PrintWriterDemo { 16 public static void main(String[] args) throws IOException { 17 // Create a data source object 18 BufferedReader bfr = new BufferedReader( new FileReader("yinzhengjie.properties" )); 19 // Create a destination object that needs to be printed 20 FileWriter fw = new FileWriter("yinzhengjie.backup" ); 21 // Turn on the automatic refresh function, if you want to turn off the automatic refresh, change it to false, or if you don't wear this parameter, the default is to turn off the automatic refresh state 22 PrintWriter pw = new PrintWriter(fw, true ) ; 23 // Start copying 24 String line =null; 25 while(((line = bfr.readLine() )!= null )) { 26 pw.print(line); 27 pw.println(); 28 } 29 //释放资源 30 pw.close(); 31 bfr.close(); 32 33 34 } 35 }