java字符輸出流PrintWriter
/**
* 測試字符輸出流PrintWriter
*/
public class TestPrintWriter {
? ?public static void main(String[] args) {
? ? ? ?try (BufferedReader br = new BufferedReader(new FileReader("iostream/testFile5.txt"));
? ? ? ? ? ? PrintWriter pw = new PrintWriter("iostream/testFile6.txt")){
? ? ? ? ? ?//PrintWriter為節(jié)點流,在實例化pw時生成了BufferedWriter(OutputStreamWriter(FileOutputStream(String fileName)))對象,實際依然使用了字節(jié)流轉(zhuǎn)字符流
? ? ? ? ? ?for (String line = br.readLine();line!=null;line = br.readLine()){
? ? ? ? ? ? ? ?pw.println(line);
? ? ? ? ? ? ? ?//使用PrintWriter拷貝字符串,.println()方法類似System.out.println,對每一行內(nèi)容輸出之后不需要手動newLine換行
? ? ? ? ? ?}
? ? ? ? ? ?pw.flush();
? ? ? ? ? ?//PrintWriter作為節(jié)點流時需要手動flush
? ? ? ?}catch (Exception e){
? ? ? ? ? ?e.printStackTrace();
? ? ? ?}
? ? ? ?
? ? ? ?try(BufferedReader br = new BufferedReader(new FileReader("iostream/testFile6.txt"));
? ? ? ? ? ?PrintWriter pw = new PrintWriter(new FileOutputStream("iostream/testFile7.txt"),true)){
? ? ? ? ? ?//PrintWriter作為處理流使用,將FileOutputStream對象傳入構造器,實例化pw時會外套BufferedWriter(OutputStreamWriter,將參數(shù)autoFlush設為true,每次println會自動flush
? ? ? ? ? ?for (String line = br.readLine();line!=null;line = br.readLine()){
? ? ? ? ? ? ? ?pw.println(line);
? ? ? ? ? ?}
? ? ? ? ? ?//無需flush,PrintWriter沒有緩沖,需要實例Buffered使用,如果構造器直接傳入Writer: new PrintWriter(new FileWriter("xxx"))這種情況不會外套BufferedWriter
? ? ? ?}catch (Exception e){
? ? ? ? ? ?e.printStackTrace();
? ? ? ?}
? ?}
}