溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java中的PrintWriter 介紹_動力節(jié)點(diǎn)Java學(xué)院整理

發(fā)布時(shí)間:2020-09-23 11:57:22 來源:腳本之家 閱讀:161 作者:mrr 欄目:編程語言

PrintWriter 介紹

PrintWriter 是字符類型的打印輸出流,它繼承于Writer。

PrintStream 用于向文本輸出流打印對象的格式化表示形式。它實(shí)現(xiàn)在 PrintStream 中的所有 print 方法。它不包含用于寫入原始字節(jié)的方法,對于這些字節(jié),程序應(yīng)該使用未編碼的字節(jié)流進(jìn)行寫入。 

PrintWriter 函數(shù)列表

PrintWriter(OutputStream out)
PrintWriter(OutputStream out, boolean autoFlush)
PrintWriter(Writer wr)
PrintWriter(Writer wr, boolean autoFlush)
PrintWriter(File file)
PrintWriter(File file, String csn)
PrintWriter(String fileName)
PrintWriter(String fileName, String csn)
PrintWriter   append(char c)
PrintWriter   append(CharSequence csq, int start, int end)
PrintWriter   append(CharSequence csq)
boolean   checkError()
void   close()
void   flush()
PrintWriter   format(Locale l, String format, Object... args)
PrintWriter   format(String format, Object... args)
void   print(float fnum)
void   print(double dnum)
void   print(String str)
void   print(Object obj)
void   print(char ch)
void   print(char[] charArray)
void   print(long lnum)
void   print(int inum)
void   print(boolean bool)
PrintWriter   printf(Locale l, String format, Object... args)
PrintWriter   printf(String format, Object... args)
void   println()
void   println(float f)
void   println(int i)
void   println(long l)
void   println(Object obj)
void   println(char[] chars)
void   println(String str)
void   println(char c)
void   println(double d)
void   println(boolean b)
void   write(char[] buf, int offset, int count)
void   write(int oneChar)
void   write(char[] buf)
void   write(String str, int offset, int count)
void   write(String str)
 
PrintWriter 源碼
 
  package java.io;
  import java.util.Objects;
  import java.util.Formatter;
  import java.util.Locale;
  import java.nio.charset.Charset;
  import java.nio.charset.IllegalCharsetNameException;
  import java.nio.charset.UnsupportedCharsetException;
 public class PrintWriter extends Writer {
   protected Writer out;
   // 自動flush
   // 所謂“自動flush”,就是每次執(zhí)行print(), println(), write()函數(shù),都會調(diào)用flush()函數(shù);
   // 而“不自動flush”,則需要我們手動調(diào)用flush()接口。
   private final boolean autoFlush;
   // PrintWriter是否右產(chǎn)生異常。當(dāng)PrintWriter有異常產(chǎn)生時(shí),會被本身捕獲,并設(shè)置trouble為true
   private boolean trouble = false;
   // 用于格式化的對象
   private Formatter formatter;
   private PrintStream psOut = null;
   // 行分割符
   private final String lineSeparator;
   // 獲取csn(字符集名字)對應(yīng)的Chaset
   private static Charset toCharset(String csn)
     throws UnsupportedEncodingException
   {
     Objects.requireNonNull(csn, "charsetName");
     try {
       return Charset.forName(csn);
     } catch (IllegalCharsetNameException|UnsupportedCharsetException unused) {
       // UnsupportedEncodingException should be thrown
       throw new UnsupportedEncodingException(csn);
     }
   }
   // 將“Writer對象out”作為PrintWriter的輸出流,默認(rèn)不會自動flush,并且采用默認(rèn)字符集。
   public PrintWriter (Writer out) {
     this(out, false);
   }
   // 將“Writer對象out”作為PrintWriter的輸出流,autoFlush的flush模式,并且采用默認(rèn)字符集。
   public PrintWriter(Writer out, boolean autoFlush) {
     super(out);
     this.out = out;
     this.autoFlush = autoFlush;
     lineSeparator = java.security.AccessController.doPrivileged(
       new sun.security.action.GetPropertyAction("line.separator"));
   }
   // 將“輸出流對象out”作為PrintWriter的輸出流,不自動flush,并且采用默認(rèn)字符集。
   public PrintWriter(OutputStream out) {
     this(out, false);
   }
   // 將“輸出流對象out”作為PrintWriter的輸出流,autoFlush的flush模式,并且采用默認(rèn)字符集。
   public PrintWriter(OutputStream out, boolean autoFlush) {
     // new OutputStreamWriter(out):將“字節(jié)類型的輸出流”轉(zhuǎn)換為“字符類型的輸出流”
     // new BufferedWriter(...): 為輸出流提供緩沖功能。
     this(new BufferedWriter(new OutputStreamWriter(out)), autoFlush);
     // save print stream for error propagation
     if (out instanceof java.io.PrintStream) {
       psOut = (PrintStream) out;
     }
   }
   // 創(chuàng)建fileName對應(yīng)的OutputStreamWriter,進(jìn)而創(chuàng)建BufferedWriter對象;然后將該BufferedWriter作為PrintWriter的輸出流,不自動flush,采用默認(rèn)字符集。
   public PrintWriter(String fileName) throws FileNotFoundException {
     this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))),
        false);
   }
   // 創(chuàng)建fileName對應(yīng)的OutputStreamWriter,進(jìn)而創(chuàng)建BufferedWriter對象;然后將該BufferedWriter作為PrintWriter的輸出流,不自動flush,采用字符集charset。
   private PrintWriter(Charset charset, File file)
     throws FileNotFoundException
   {
     this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset)),
        false);
   }
   // 創(chuàng)建fileName對應(yīng)的OutputStreamWriter,進(jìn)而創(chuàng)建BufferedWriter對象;然后將該BufferedWriter作為PrintWriter的輸出流,不自動flush,采用csn字符集。
   public PrintWriter(String fileName, String csn)
     throws FileNotFoundException, UnsupportedEncodingException
   {
     this(toCharset(csn), new File(fileName));
   }
   // 創(chuàng)建file對應(yīng)的OutputStreamWriter,進(jìn)而創(chuàng)建BufferedWriter對象;然后將該BufferedWriter作為PrintWriter的輸出流,不自動flush,采用默認(rèn)字符集。
   public PrintWriter(File file) throws FileNotFoundException {
     this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))),
        false);
   }
   // 創(chuàng)建file對應(yīng)的OutputStreamWriter,進(jìn)而創(chuàng)建BufferedWriter對象;然后將該BufferedWriter作為PrintWriter的輸出流,不自動flush,采用csn字符集。
   public PrintWriter(File file, String csn)
     throws FileNotFoundException, UnsupportedEncodingException
   {
     this(toCharset(csn), file);
   }
   private void ensureOpen() throws IOException {
     if (out == null)
       throw new IOException("Stream closed");
   }
   // flush“PrintWriter輸出流中的數(shù)據(jù)”。
   public void flush() {
     try {
       synchronized (lock) {
         ensureOpen();
         out.flush();
       }
     }
     catch (IOException x) {
       trouble = true;
     }
   }
   public void close() {
     try {
       synchronized (lock) {
         if (out == null)
           return;
         out.close();
         out = null;
       }
     }
     catch (IOException x) {
       trouble = true;
     }
   }
   // flush“PrintWriter輸出流緩沖中的數(shù)據(jù)”,并檢查錯(cuò)誤
   public boolean checkError() {
     if (out != null) {
       flush();
     }
     if (out instanceof java.io.PrintWriter) {
       PrintWriter pw = (PrintWriter) out;
       return pw.checkError();
     } else if (psOut != null) {
       return psOut.checkError();
     }
     return trouble;
   }
   protected void setError() {
     trouble = true;
   }
   protected void clearError() {
     trouble = false;
   }
   // 將字符c寫入到“PrintWriter輸出流”中。c雖然是int類型,但實(shí)際只會寫入一個(gè)字符
   public void write(int c) {
     try {
       synchronized (lock) {
         ensureOpen();
         out.write(c);
       }
     }
     catch (InterruptedIOException x) {
       Thread.currentThread().interrupt();
     }
     catch (IOException x) {
       trouble = true;
     }
   }
   // 將“buf中從off開始的len個(gè)字符”寫入到“PrintWriter輸出流”中。
   public void write(char buf[], int off, int len) {
     try {
       synchronized (lock) {
         ensureOpen();
         out.write(buf, off, len);
       }
     }
     catch (InterruptedIOException x) {
       Thread.currentThread().interrupt();
     }
     catch (IOException x) {
       trouble = true;
     }
   }
   // 將“buf中的全部數(shù)據(jù)”寫入到“PrintWriter輸出流”中。
   public void write(char buf[]) {
     write(buf, , buf.length);
   }
   // 將“字符串s中從off開始的len個(gè)字符”寫入到“PrintWriter輸出流”中。
   public void write(String s, int off, int len) {
     try {
       synchronized (lock) {
         ensureOpen();
         out.write(s, off, len);
       }
     }
     catch (InterruptedIOException x) {
       Thread.currentThread().interrupt();
     }
     catch (IOException x) {
       trouble = true;
     }
   }
   // 將“字符串s”寫入到“PrintWriter輸出流”中。
   public void write(String s) {
     write(s, , s.length());
   }
   // 將“換行符”寫入到“PrintWriter輸出流”中。
   private void newLine() {
     try {
       synchronized (lock) {
         ensureOpen();
         out.write(lineSeparator);
         if (autoFlush)
           out.flush();
       }
     }
     catch (InterruptedIOException x) {
       Thread.currentThread().interrupt();
     }
     catch (IOException x) {
       trouble = true;
     }
   }
   // 將“boolean數(shù)據(jù)對應(yīng)的字符串”寫入到“PrintWriter輸出流”中,print實(shí)際調(diào)用的是write函數(shù)
   public void print(boolean b) {
     write(b ? "true" : "false");
   }
   // 將“字符c對應(yīng)的字符串”寫入到“PrintWriter輸出流”中,print實(shí)際調(diào)用的是write函數(shù)
   public void print(char c) {
     write(c);
   }
   // 將“int數(shù)據(jù)i對應(yīng)的字符串”寫入到“PrintWriter輸出流”中,print實(shí)際調(diào)用的是write函數(shù)
   public void print(int i) {
     write(String.valueOf(i));
   }
   // 將“l(fā)ong型數(shù)據(jù)l對應(yīng)的字符串”寫入到“PrintWriter輸出流”中,print實(shí)際調(diào)用的是write函數(shù)
   public void print(long l) {
     write(String.valueOf(l));
   }
   // 將“float數(shù)據(jù)f對應(yīng)的字符串”寫入到“PrintWriter輸出流”中,print實(shí)際調(diào)用的是write函數(shù)
   public void print(float f) {
     write(String.valueOf(f));
   }
   // 將“double數(shù)據(jù)d對應(yīng)的字符串”寫入到“PrintWriter輸出流”中,print實(shí)際調(diào)用的是write函數(shù)
   public void print(double d) {
     write(String.valueOf(d));
   }
   // 將“字符數(shù)組s”寫入到“PrintWriter輸出流”中,print實(shí)際調(diào)用的是write函數(shù)
   public void print(char s[]) {
     write(s);
   }
   // 將“字符串?dāng)?shù)據(jù)s”寫入到“PrintWriter輸出流”中,print實(shí)際調(diào)用的是write函數(shù)
   public void print(String s) {
     if (s == null) {
       s = "null";
     }
     write(s);
   }
   // 將“對象obj對應(yīng)的字符串”寫入到“PrintWriter輸出流”中,print實(shí)際調(diào)用的是write函數(shù)
   public void print(Object obj) {
     write(String.valueOf(obj));
   }
   // 將“換行符”寫入到“PrintWriter輸出流”中,println實(shí)際調(diào)用的是write函數(shù)
   public void println() {
     newLine();
   }
   // 將“boolean數(shù)據(jù)對應(yīng)的字符串+換行符”寫入到“PrintWriter輸出流”中,println實(shí)際調(diào)用的是write函數(shù)
   public void println(boolean x) {
     synchronized (lock) {
       print(x);
       println();
     }
   }
   // 將“字符x對應(yīng)的字符串+換行符”寫入到“PrintWriter輸出流”中,println實(shí)際調(diào)用的是write函數(shù)
   public void println(char x) {
     synchronized (lock) {
       print(x);
       println();
     }
   }
   // 將“int數(shù)據(jù)對應(yīng)的字符串+換行符”寫入到“PrintWriter輸出流”中,println實(shí)際調(diào)用的是write函數(shù)
   public void println(int x) {
     synchronized (lock) {
       print(x);
       println();
     }
   }
   // 將“l(fā)ong數(shù)據(jù)對應(yīng)的字符串+換行符”寫入到“PrintWriter輸出流”中,println實(shí)際調(diào)用的是write函數(shù)
   public void println(long x) {
     synchronized (lock) {
       print(x);
       println();
     }
   }
   // 將“float數(shù)據(jù)對應(yīng)的字符串+換行符”寫入到“PrintWriter輸出流”中,println實(shí)際調(diào)用的是write函數(shù)
   public void println(float x) {
     synchronized (lock) {
       print(x);
       println();
     }
   }
   // 將“double數(shù)據(jù)對應(yīng)的字符串+換行符”寫入到“PrintWriter輸出流”中,println實(shí)際調(diào)用的是write函數(shù)
   public void println(double x) {
     synchronized (lock) {
       print(x);
       println();
     }
   }
   // 將“字符數(shù)組x+換行符”寫入到“PrintWriter輸出流”中,println實(shí)際調(diào)用的是write函數(shù)
   public void println(char x[]) {
     synchronized (lock) {
       print(x);
       println();
     }
   }
   // 將“字符串x+換行符”寫入到“PrintWriter輸出流”中,println實(shí)際調(diào)用的是write函數(shù)
   public void println(String x) {
     synchronized (lock) {
       print(x);
       println();
     }
   }
   // 將“對象o對應(yīng)的字符串+換行符”寫入到“PrintWriter輸出流”中,println實(shí)際調(diào)用的是write函數(shù)
   public void println(Object x) {
     String s = String.valueOf(x);
     synchronized (lock) {
       print(s);
       println();
     }
   }
   // 將“數(shù)據(jù)args”根據(jù)“默認(rèn)Locale值(區(qū)域?qū)傩?”按照format格式化,并寫入到“PrintWriter輸出流”中
   public PrintWriter printf(String format, Object ... args) {
     return format(format, args);
   }
   // 將“數(shù)據(jù)args”根據(jù)“Locale值(區(qū)域?qū)傩?”按照format格式化,并寫入到“PrintWriter輸出流”中
   public PrintWriter printf(Locale l, String format, Object ... args) {
     return format(l, format, args);
   }
   // 根據(jù)“默認(rèn)的Locale值(區(qū)域?qū)傩?”來格式化數(shù)據(jù)
   public PrintWriter format(String format, Object ... args) {
     try {
       synchronized (lock) {
         ensureOpen();
         if ((formatter == null)
           || (formatter.locale() != Locale.getDefault()))
           formatter = new Formatter(this);
         formatter.format(Locale.getDefault(), format, args);
         if (autoFlush)
           out.flush();
       }
     } catch (InterruptedIOException x) {
       Thread.currentThread().interrupt();
     } catch (IOException x) {
       trouble = true;
     }
     return this;
   }
   // 根據(jù)“Locale值(區(qū)域?qū)傩?”來格式化數(shù)據(jù)
   public PrintWriter format(Locale l, String format, Object ... args) {
     try {
       synchronized (lock) {
         ensureOpen();
         if ((formatter == null) || (formatter.locale() != l))
           formatter = new Formatter(this, l);
         formatter.format(l, format, args);
         if (autoFlush)
           out.flush();
       }
     } catch (InterruptedIOException x) {
       Thread.currentThread().interrupt();
     } catch (IOException x) {
       trouble = true;
     }
     return this;
   }
   // 將“字符序列的全部字符”追加到“PrintWriter輸出流中”
   public PrintWriter append(CharSequence csq) {
     if (csq == null)
       write("null");
     else
       write(csq.toString());
     return this;
   }
   // 將“字符序列從start(包括)到end(不包括)的全部字符”追加到“PrintWriter輸出流中”
   public PrintWriter append(CharSequence csq, int start, int end) {
     CharSequence cs = (csq == null ? "null" : csq);
     write(cs.subSequence(start, end).toString());
     return this;
   }
   // 將“字符c”追加到“PrintWriter輸出流中”
   public PrintWriter append(char c) {
     write(c);
     return this;
   }
 }

 示例代碼

關(guān)于PrintWriter中API的詳細(xì)用法,參考示例代碼(PrintWriterTest.java): 

import java.io.PrintWriter;
  import java.io.File;
  import java.io.FileOutputStream;
  import java.io.IOException;
  /**
  * PrintWriter 的示例程序
  *
  * 
  */
 public class PrintWriterTest {
   public static void main(String[] args) {
     // 下面?zhèn)€函數(shù)的作用都是一樣:都是將字母“abcde”寫入到文件“file.txt”中。
     // 任選一個(gè)執(zhí)行即可!
     testPrintWriterConstrutor() ;
     //testPrintWriterConstrutor() ;
     //testPrintWriterConstrutor() ;
     // 測試write(), print(), println(), printf()等接口。
     testPrintWriterAPIS() ;
   }
   /**
    * PrintWriter(OutputStream out) 的測試函數(shù)
    *
    * 函數(shù)的作用,就是將字母“abcde”寫入到文件“file.txt”中
    */
   private static void testPrintWriterConstrutor() {
     final char[] arr={'a', 'b', 'c', 'd', 'e' };
     try {
       // 創(chuàng)建文件“file.txt”的File對象
       File file = new File("file.txt");
       // 創(chuàng)建文件對應(yīng)FileOutputStream
       PrintWriter out = new PrintWriter(
           new FileOutputStream(file));
       // 將“字節(jié)數(shù)組arr”全部寫入到輸出流中
       out.write(arr);
       // 關(guān)閉輸出流
       out.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   /**
    * PrintWriter(File file) 的測試函數(shù)
    *
    * 函數(shù)的作用,就是將字母“abcde”寫入到文件“file.txt”中
    */
   private static void testPrintWriterConstrutor() {
     final char[] arr={'a', 'b', 'c', 'd', 'e' };
     try {
       File file = new File("file.txt");
       PrintWriter out = new PrintWriter(file);
       out.write(arr);
       out.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   /**
    * PrintWriter(String fileName) 的測試函數(shù)
    *
    * 函數(shù)的作用,就是將字母“abcde”寫入到文件“file.txt”中
    */
   private static void testPrintWriterConstrutor() {
     final char[] arr={'a', 'b', 'c', 'd', 'e' };
     try {
       PrintWriter out = new PrintWriter("file.txt");
       out.write(arr);
       out.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   /**
    * 測試write(), print(), println(), printf()等接口。
    */
   private static void testPrintWriterAPIS() {
     final char[] arr={'a', 'b', 'c', 'd', 'e' };
     try {
       // 創(chuàng)建文件對應(yīng)FileOutputStream
       PrintWriter out = new PrintWriter("other.txt");
       // 將字符串“hello PrintWriter”+回車符,寫入到輸出流中
       out.println("hello PrintWriter");
       // 將x寫入到輸出流中
       // x對應(yīng)ASCII碼的字母'A',也就是寫入字符'A'
       out.write(x);
       // 將字符串""寫入到輸出流中。
       // out.print(x); 等價(jià)于 out.write(String.valueOf(x));
       out.print(x);
       // 將字符'B'追加到輸出流中
       out.append('B').append("CDEF");
       // 將"CDE is " + 回車 寫入到輸出流中
       String str = "GHI";
       int num = ;
       out.printf("%s is %d\n", str, num);
       out.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }

運(yùn)行上面的代碼,會在源碼所在目錄生成兩個(gè)文件“file.txt”和“other.txt”。

file.txt的內(nèi)容如下:

abcde

other.txt的內(nèi)容如下:

hello PrintWriter
A65BCDEFGHI is 5

以上所述是小編給大家介紹的Java中的PrintWriter知識,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時(shí)回復(fù)大家的。在此也非常感謝大家對億速云網(wǎng)站的支持!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI