目錄
1. PrintWriter 介紹
2. PrintWriter 源碼
3. 示例代碼
PrintWriter 是字符類型的列印輸出流,它繼承於Writer。
PrintStream 用於向文本輸出流列印對象的格式化表示形式。它實現在 PrintStream 中的所有 print 方法。它不包含用於寫入原始字節的方法,對於這些字節,程序應該使用未編碼的字節流進行寫入。
PrintWriter 函數列表
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)
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」,就是每次執行print(), println(), write()函數,都會調用flush()函數;
// 而「不自動flush」,則需要我們手動調用flush()接口。
private final boolean autoFlush;
// PrintWriter是否右產生異常。當PrintWriter有異常產生時,會被本身捕獲,並設置trouble為true
private boolean trouble = false;
// 用于格式化的對象
private Formatter formatter;
private PrintStream psOut = null;
// 行分割符
private final String lineSeparator;
// 獲取csn(字符集名字)對應的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的輸出流,默認不會自動flush,並且採用默認字符集。
public PrintWriter (Writer out) {
this(out, false);
}
// 將「Writer對象out」作為PrintWriter的輸出流,autoFlush的flush模式,並且採用默認字符集。
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,並且採用默認字符集。
public PrintWriter(OutputStream out) {
this(out, false);
}
// 將「輸出流對象out」作為PrintWriter的輸出流,autoFlush的flush模式,並且採用默認字符集。
public PrintWriter(OutputStream out, boolean autoFlush) {
// new OutputStreamWriter(out):將「字節類型的輸出流」轉換為「字符類型的輸出流」
// new BufferedWriter(...): 為輸出流提供緩衝功能。
this(new BufferedWriter(new OutputStreamWriter(out)), autoFlush);
// save print stream for error propagation
if (out instanceof java.io.PrintStream) {
psOut = (PrintStream) out;
}
}
// 創建fileName對應的OutputStreamWriter,進而創建BufferedWriter對象;然後將該BufferedWriter作為PrintWriter的輸出流,不自動flush,採用默認字符集。
public PrintWriter(String fileName) throws FileNotFoundException {
this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))),
false);
}
// 創建fileName對應的OutputStreamWriter,進而創建BufferedWriter對象;然後將該BufferedWriter作為PrintWriter的輸出流,不自動flush,採用字符集charset。
private PrintWriter(Charset charset, File file)
throws FileNotFoundException
{
this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset)),
false);
}
// 創建fileName對應的OutputStreamWriter,進而創建BufferedWriter對象;然後將該BufferedWriter作為PrintWriter的輸出流,不自動flush,採用csn字符集。
public PrintWriter(String fileName, String csn)
throws FileNotFoundException, UnsupportedEncodingException
{
this(toCharset(csn), new File(fileName));
}
// 創建file對應的OutputStreamWriter,進而創建BufferedWriter對象;然後將該BufferedWriter作為PrintWriter的輸出流,不自動flush,採用默認字符集。
public PrintWriter(File file) throws FileNotFoundException {
this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))),
false);
}
// 創建file對應的OutputStreamWriter,進而創建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輸出流中的數據」。
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輸出流緩衝中的數據」,並檢查錯誤
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類型,但實際只會寫入一個字符
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個字符」寫入到「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中的全部數據」寫入到「PrintWriter輸出流」中。
public void write(char buf[]) {
write(buf, 0, buf.length);
}
// 將「字符串s中從off開始的len個字符」寫入到「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, 0, 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數據對應的字符串」寫入到「PrintWriter輸出流」中,print實際調用的是write函數
public void print(boolean b) {
write(b ? "true" : "false");
}
// 將「字符c對應的字符串」寫入到「PrintWriter輸出流」中,print實際調用的是write函數
public void print(char c) {
write(c);
}
// 將「int數據i對應的字符串」寫入到「PrintWriter輸出流」中,print實際調用的是write函數
public void print(int i) {
write(String.valueOf(i));
}
// 將「long型數據l對應的字符串」寫入到「PrintWriter輸出流」中,print實際調用的是write函數
public void print(long l) {
write(String.valueOf(l));
}
// 將「float數據f對應的字符串」寫入到「PrintWriter輸出流」中,print實際調用的是write函數
public void print(float f) {
write(String.valueOf(f));
}
// 將「double數據d對應的字符串」寫入到「PrintWriter輸出流」中,print實際調用的是write函數
public void print(double d) {
write(String.valueOf(d));
}
// 將「字符數組s」寫入到「PrintWriter輸出流」中,print實際調用的是write函數
public void print(char s[]) {
write(s);
}
// 將「字符串數據s」寫入到「PrintWriter輸出流」中,print實際調用的是write函數
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
// 將「對象obj對應的字符串」寫入到「PrintWriter輸出流」中,print實際調用的是write函數
public void print(Object obj) {
write(String.valueOf(obj));
}
// 將「換行符」寫入到「PrintWriter輸出流」中,println實際調用的是write函數
public void println() {
newLine();
}
// 將「boolean數據對應的字符串+換行符」寫入到「PrintWriter輸出流」中,println實際調用的是write函數
public void println(boolean x) {
synchronized (lock) {
print(x);
println();
}
}
// 將「字符x對應的字符串+換行符」寫入到「PrintWriter輸出流」中,println實際調用的是write函數
public void println(char x) {
synchronized (lock) {
print(x);
println();
}
}
// 將「int數據對應的字符串+換行符」寫入到「PrintWriter輸出流」中,println實際調用的是write函數
public void println(int x) {
synchronized (lock) {
print(x);
println();
}
}
// 將「long數據對應的字符串+換行符」寫入到「PrintWriter輸出流」中,println實際調用的是write函數
public void println(long x) {
synchronized (lock) {
print(x);
println();
}
}
// 將「float數據對應的字符串+換行符」寫入到「PrintWriter輸出流」中,println實際調用的是write函數
public void println(float x) {
synchronized (lock) {
print(x);
println();
}
}
// 將「double數據對應的字符串+換行符」寫入到「PrintWriter輸出流」中,println實際調用的是write函數
public void println(double x) {
synchronized (lock) {
print(x);
println();
}
}
// 將「字符數組x+換行符」寫入到「PrintWriter輸出流」中,println實際調用的是write函數
public void println(char x[]) {
synchronized (lock) {
print(x);
println();
}
}
// 將「字符串x+換行符」寫入到「PrintWriter輸出流」中,println實際調用的是write函數
public void println(String x) {
synchronized (lock) {
print(x);
println();
}
}
// 將「對象o對應的字符串+換行符」寫入到「PrintWriter輸出流」中,println實際調用的是write函數
public void println(Object x) {
String s = String.valueOf(x);
synchronized (lock) {
print(s);
println();
}
}
// 將「數據args」根據「默認Locale值(區域屬性)」按照format格式化,並寫入到「PrintWriter輸出流」中
public PrintWriter printf(String format, Object ... args) {
return format(format, args);
}
// 將「數據args」根據「Locale值(區域屬性)」按照format格式化,並寫入到「PrintWriter輸出流」中
public PrintWriter printf(Locale l, String format, Object ... args) {
return format(l, format, args);
}
// 根據「默認的Locale值(區域屬性)」來格式化數據
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;
}
// 根據「Locale值(區域屬性)」來格式化數據
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;
}
}
關於PrintWriter中API的詳細用法,參考示例代碼(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) {
// 下面3個函數的作用都是一樣:都是將字母「abcde」寫入到文件「file.txt」中。
// 任選一個執行即可!
testPrintWriterConstrutor1() ;
//testPrintWriterConstrutor2() ;
//testPrintWriterConstrutor3() ;
// 測試write(), print(), println(), printf()等接口。
testPrintWriterAPIS() ;
}
/**
* PrintWriter(OutputStream out) 的測試函數
*
* 函數的作用,就是將字母「abcde」寫入到文件「file.txt」中
*/
private static void testPrintWriterConstrutor1() {
final char[] arr={'a', 'b', 'c', 'd', 'e' };
try {
// 創建文件「file.txt」的File對象
File file = new File("file.txt");
// 創建文件對應FileOutputStream
PrintWriter out = new PrintWriter(
new FileOutputStream(file));
// 將「字節數組arr」全部寫入到輸出流中
out.write(arr);
// 關閉輸出流
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* PrintWriter(File file) 的測試函數
*
* 函數的作用,就是將字母「abcde」寫入到文件「file.txt」中
*/
private static void testPrintWriterConstrutor2() {
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) 的測試函數
*
* 函數的作用,就是將字母「abcde」寫入到文件「file.txt」中
*/
private static void testPrintWriterConstrutor3() {
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 {
// 創建文件對應FileOutputStream
PrintWriter out = new PrintWriter("other.txt");
// 將字符串「hello PrintWriter」+回車符,寫入到輸出流中
out.println("hello PrintWriter");
// 將0x41寫入到輸出流中
// 0x41對應ASCII碼的字母'A',也就是寫入字符'A'
out.write(0x41);
// 將字符串"65"寫入到輸出流中。
// out.print(0x41); 等價於 out.write(String.valueOf(0x41));
out.print(0x41);
// 將字符'B'追加到輸出流中
out.append('B').append("CDEF");
// 將"CDE is 5" + 回車 寫入到輸出流中
String str = "GHI";
int num = 5;
out.printf("%s is %d\n", str, num);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
運行上面的代碼,會在源碼所在目錄生成兩個文件「file.txt」和「other.txt」。
file.txt的內容如下:
abcde
other.txt的內容如下:
hello PrintWriter
A65BCDEFGHI is 5
RandomAccessFile 是隨機訪問文件(包括讀/寫)的類。它支持對文件隨機訪問的讀取和寫入,即我們可以從指定的位置讀取/寫入文件數據。
需要注意的是,RandomAccessFile 雖然屬於java.io包,但它不是InputStream或者OutputStream的子類;它也不同於FileInputStream和FileOutputStream。FileInputStream 只能對文件進行讀操作,而FileOutputStream 只能對文件進行寫操作;但是,RandomAccessFile 同時支持文件的讀和寫,並且它支持隨機訪問。
RandomAccessFile 函數列表
RandomAccessFile(File file, String mode)
RandomAccessFile(String fileName, String mode)
void close()
synchronized final FileChannel getChannel()
final FileDescriptor getFD()
long getFilePointer()
long length()
int read(byte[] buffer, int byteOffset, int byteCount)
int read(byte[] buffer)
int read()
final boolean readBoolean()
final byte readByte()
final char readChar()
final double readDouble()
final float readFloat()
final void readFully(byte[] dst)
final void readFully(byte[] dst, int offset, int byteCount)
final int readInt()
final String readLine()
final long readLong()
final short readShort()
final String readUTF()
final int readUnsignedByte()
final int readUnsignedShort()
void seek(long offset)
void setLength(long newLength)
int skipBytes(int count)
void write(int oneByte)
void write(byte[] buffer, int byteOffset, int byteCount)
void write(byte[] buffer)
final void writeBoolean(boolean val)
final void writeByte(int val)
final void writeBytes(String str)
final void writeChar(int val)
final void writeChars(String str)
final void writeDouble(double val)
final void writeFloat(float val)
final void writeInt(int val)
final void writeLong(long val)
final void writeShort(int val)
final void writeUTF(String str)
RandomAccessFile共有4種模式:"r", "rw", "rws"和"rwd"。
"r" 以只讀方式打開。調用結果對象的任何 write 方法都將導致拋出 IOException。
"rw" 打開以便讀取和寫入。
"rws" 打開以便讀取和寫入。相對於 "rw","rws" 還要求對「文件的內容」或「元數據」的每個更新都同步寫入到基礎存儲設備。
"rwd" 打開以便讀取和寫入,相對於 "rw","rwd" 還要求對「文件的內容」的每個更新都同步寫入到基礎存儲設備。
說明:
(01) 什麼是「元數據」,即metadata?
英文解釋如下:
The definition of metadata is "data about other data." With a file system, the data is contained in its files and directories, and the metadata tracks information about each of these objects: Is it a regular file, a directory, or a link? What is its size, creation date, last modified date, file owner, group owner, and access permissions?
大致意思是:
metadata是「關於數據的數據」。在文件系統中,數據被包含在文件和文件夾中;metadata信息包括:「數據是一個文件,一個目錄還是一個連結」,「數據的創建時間(簡稱ctime)」,「最後一次修改時間(簡稱mtime)」,「數據擁有者」,「數據擁有群組」,「訪問權限」等等。
(02) "rw", "rws", "rwd" 的區別。
當操作的文件是存儲在本地的基礎存儲設備上時(如硬碟, NandFlash等),"rws" 或 "rwd", "rw" 才有區別。
當模式是 "rws" 並且 操作的是基礎存儲設備上的文件;那麼,每次「更改文件內容[如write()寫入數據]」 或 「修改文件元數據(如文件的mtime)」時,都會將這些改變同步到基礎存儲設備上。
當模式是 "rwd" 並且 操作的是基礎存儲設備上的文件;那麼,每次「更改文件內容[如write()寫入數據]」時,都會將這些改變同步到基礎存儲設備上。
當模式是 "rw" 並且 操作的是基礎存儲設備上的文件;那麼,關閉文件時,會將「文件內容的修改」同步到基礎存儲設備上。至於,「更改文件內容」時,是否會立即同步,取決於系統底層實現。
源碼如下:
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.PrintStream;;
import java.io.RandomAccessFile;
import java.io.IOException;
/**
* RandomAccessFile 測試程序
*
* 運行結果(輸出如下):
* c1=a
* c2=b
* buf=9876543210
*
* 此外,
* (01) 在源文件所在目錄生成了file.txt。
* (02) 注意RandomAccessFile寫入boolean, byte, char, int,所佔的字符個數。
*
*/
public class RandomAccessFileTest {
private static final String FileName = "file.txt";
public static void main(String[] args) {
// 若文件「file.txt」存在,則刪除該文件。
File file = new File(FileName);
if (file.exists())
file.delete();
testCreateWrite();
testAppendWrite();
testRead();
}
/**
* 若「file.txt」不存在的話,則新建文件,並向文件中寫入內容
*/
private static void testCreateWrite() {
try {
// 創建文件「file.txt」對應File對象
File file = new File(FileName);
// 創建文件「file.txt」對應的RandomAccessFile對象
RandomAccessFile raf = new RandomAccessFile(file, "rw");
// 向「文件中」寫入26個字母+回車
raf.writeChars("abcdefghijklmnopqrstuvwxyz\n");
// 向「文件中」寫入"9876543210"+回車
raf.writeChars("9876543210\n");
raf.close();
} catch(IOException e) {
e.printStackTrace();
}
}
/**
* 向文件末尾追加內容
*/
private static void testAppendWrite() {
try {
// 創建文件「file.txt」對應File對象
File file = new File(FileName);
// 創建文件「file.txt」對應的RandomAccessFile對象
RandomAccessFile raf = new RandomAccessFile(file, "rw");
// 獲取文件長度
long fileLen = raf.length();
// 將位置定位到「文件末尾」
raf.seek(fileLen);
// 以下向raf文件中寫數據
raf.writeBoolean(true); // 佔1個字節
raf.writeByte(0x41); // 佔1個字節
raf.writeChar('a'); // 佔2個字節
raf.writeShort(0x3c3c); // 佔2個字節
raf.writeInt(0x75); // 佔4個字節
raf.writeLong(0x1234567890123456L); // 佔8個字節
raf.writeFloat(4.7f); // 佔4個字節
raf.writeDouble(8.256);// 佔8個字節
raf.writeUTF("UTF嚴"); // UTF-8格式寫入
raf.writeChar('\n'); // 佔2個字符。「換行符」
raf.close();
} catch(IOException e) {
e.printStackTrace();
}
}
/**
* 通過RandomAccessFile讀取文件
*/
private static void testRead() {
try {
// 創建文件「file.txt」對應File對象
File file = new File(FileName);
// 創建文件「file.txt」對應的RandomAccessFile對象,以只讀方式打開
RandomAccessFile raf = new RandomAccessFile(file, "r");
// 讀取一個字符
char c1 = raf.readChar();
System.out.println("c1="+c1);
// 讀取一個字符
char c2 = raf.readChar();
System.out.println("c2="+c2);
// 跳過54個字節。
raf.seek(54);
// 測試read(byte[] buffer, int byteOffset, int byteCount)
byte[] buf = new byte[20];
raf.read(buf, 0, buf.length);
System.out.println("buf="+(new String(buf)));
raf.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
運行結果:
c1=a
c2=b
buf=9876543210
結果說明:程序會在源文件所在目錄生成file.txt;file.txt的內容如下:
file.txt對應的16進位內容如下: