Java IO - DataFormatted

来源:互联网 发布:2017qq空间淘宝客推广 编辑:程序博客网 时间:2024/04/30 06:39

Java IO - DataFormatted

目录

    • Java IO - DataFormatted
    • 目录
    • PrintStream
    • PrintWriter


PrintStream 和 PrintWriter


PrintStream

package java.io;import java.util.Formatter;import java.util.Locale;import java.nio.charset.Charset;import java.nio.charset.IllegalCharsetNameException;import java.nio.charset.UnsupportedCharsetException;/** * PrintStream 是一个包装类,从名字上可以看出它可以提供各种数据的打印形式。 * 而且,PrintStream 不会抛出异常。再者,PrintStream 可以设置成自动 flush。 * 所有 PrintStream 打印的字符都会在底层被转变成字节(使用系统的默认编码),如果想要写入字符,考虑使用 PrintWriter */public class PrintStream extends FilterOutputStream    implements Appendable, Closeable{    private final boolean autoFlush;    private boolean trouble = false;    private Formatter formatter;    /**     * 底层使用的还是 BufferedWriter 和 OutputStreamWriter     */    private BufferedWriter textOut;    private OutputStreamWriter charOut;    /**     * PrintStream 在系统初始化的时候更早加载,所以为了不依赖 java.util.Objects.requireNonNull. 在这里事先定义了。     */    private static <T> T requireNonNull(T obj, String message) {        if (obj == null)            throw new NullPointerException(message);        return obj;    }    /**     * 给定字符集名称返回一个字符集对象.     */    private static Charset toCharset(String csn)        throws UnsupportedEncodingException    {        requireNonNull(csn, "charsetName");        try {            return Charset.forName(csn);        } catch (IllegalCharsetNameException|UnsupportedCharsetException unused) {            // UnsupportedEncodingException should be thrown            throw new UnsupportedEncodingException(csn);        }    }    /* 给定 OutputStream,创建一个 PrintStream */    private PrintStream(boolean autoFlush, OutputStream out) {        super(out);        this.autoFlush = autoFlush;        this.charOut = new OutputStreamWriter(this);        this.textOut = new BufferedWriter(charOut);    }    private PrintStream(boolean autoFlush, OutputStream out, Charset charset) {        super(out);        this.autoFlush = autoFlush;        this.charOut = new OutputStreamWriter(this, charset);        this.textOut = new BufferedWriter(charOut);    }    // 为了优先校验 charset!!!    private PrintStream(boolean autoFlush, Charset charset, OutputStream out)        throws UnsupportedEncodingException    {        this(autoFlush, out, charset);    }    /**     * 不会自动 刷新     */    public PrintStream(OutputStream out) {        this(out, false);    }    public PrintStream(OutputStream out, boolean autoFlush) {        this(autoFlush, requireNonNull(out, "Null output stream"));    }    public PrintStream(OutputStream out, boolean autoFlush, String encoding)        throws UnsupportedEncodingException    {        this(autoFlush,             requireNonNull(out, "Null output stream"),             toCharset(encoding));    }    public PrintStream(String fileName) throws FileNotFoundException {        this(false, new FileOutputStream(fileName));    }    public PrintStream(String fileName, String csn)        throws FileNotFoundException, UnsupportedEncodingException    {        // ensure charset is checked before the file is opened        this(false, toCharset(csn), new FileOutputStream(fileName));    }    public PrintStream(File file) throws FileNotFoundException {        this(false, new FileOutputStream(file));    }    public PrintStream(File file, String csn)        throws FileNotFoundException, UnsupportedEncodingException    {        // ensure charset is checked before the file is opened        this(false, toCharset(csn), new FileOutputStream(file));    }    /** Check to make sure that the stream has not been closed */    private void ensureOpen() throws IOException {        if (out == null)            throw new IOException("Stream closed");    }    /**     * 把缓存的所有数据写入到 outputstream 中,然后再刷新这个 outputstream     */    public void flush() {        synchronized (this) {            try {                ensureOpen();                out.flush();            }            catch (IOException x) {                trouble = true;            }        }    }    private boolean closing = false; /* To avoid recursive closing */    public void close() {        synchronized (this) {            if (! closing) {                closing = true;                try {                    textOut.close();                    out.close(); // 先 flush                }                catch (IOException x) {                    trouble = true;                }                textOut = null;                charOut = null;                out = null;            }        }    }    public boolean checkError() {        if (out != null)            flush(); // 先 flush        if (out instanceof java.io.PrintStream) {            PrintStream ps = (PrintStream) out;            return ps.checkError();        }        return trouble;    }    protected void setError() {        trouble = true;    }    protected void clearError() {        trouble = false;    }    /*     * Exception-catching, synchronized output operations,     * which also implement the write() methods of OutputStream     */    /**     * 写一个字节,如果这个字节是 \n 并且 autoFlush 开启了,那么就flush输出流,下同     */    public void write(int b) {        try {            synchronized (this) {                ensureOpen();                out.write(b);                if ((b == '\n') && autoFlush)                    out.flush();            }        }        catch (InterruptedIOException x) {            Thread.currentThread().interrupt();        }        catch (IOException x) {            trouble = true;        }    }    public void write(byte buf[], int off, int len) {        try {            synchronized (this) {                ensureOpen();                out.write(buf, off, len);                if (autoFlush) // 只判断 autoFlush                    out.flush();            }        }        catch (InterruptedIOException x) {            Thread.currentThread().interrupt();        }        catch (IOException x) {            trouble = true;        }    }    /*     * 文本和字符流直接就把数据刷到 outputstream中了     */    private void write(char buf[]) {        try {            synchronized (this) {                ensureOpen();                textOut.write(buf);                textOut.flushBuffer();                charOut.flushBuffer();                if (autoFlush) {                    for (int i = 0; i < buf.length; i++)                        if (buf[i] == '\n')                            out.flush();                }            }        }        catch (InterruptedIOException x) {            Thread.currentThread().interrupt();        }        catch (IOException x) {            trouble = true;        }    }    private void write(String s) {        try {            synchronized (this) {                ensureOpen();                textOut.write(s);                textOut.flushBuffer();                charOut.flushBuffer();                if (autoFlush && (s.indexOf('\n') >= 0))                    out.flush();            }        }        catch (InterruptedIOException x) {            Thread.currentThread().interrupt();        }        catch (IOException x) {            trouble = true;        }    }    private void newLine() {        try {            synchronized (this) {                ensureOpen();                textOut.newLine();                textOut.flushBuffer();                charOut.flushBuffer();                if (autoFlush)                    out.flush();            }        }        catch (InterruptedIOException x) {            Thread.currentThread().interrupt();        }        catch (IOException x) {            trouble = true;        }    }    /* Methods that do not terminate lines */    /**     * 打印一个 boolean 类型数据,实际写入的是 经过编码的字符串     */    public void print(boolean b) {        write(b ? "true" : "false");    }    /**     * 打印一个字符,会被编码     */    public void print(char c) {        write(String.valueOf(c));    }    /**     * 写入一个整形数字,产生的字符串会被编码     */    public void print(int i) {        write(String.valueOf(i));    }    public void print(long l) {        write(String.valueOf(l));    }    public void print(float f) {        write(String.valueOf(f));    }    public void print(double d) {        write(String.valueOf(d));    }    public void print(char s[]) {        write(s);    }    public void print(String s) {        if (s == null) {            s = "null";        }        write(s);    }    public void print(Object obj) {        write(String.valueOf(obj));    }    /* Methods that do terminate lines */    /**     * 终结行,添加行结束符     */    public void println() {        newLine();    }    public void println(boolean x) {        synchronized (this) {            print(x);            newLine();        }    }    public void println(char x) {        synchronized (this) {            print(x);            newLine();        }    }    public void println(int x) {        synchronized (this) {            print(x);            newLine();        }    }    public void println(long x) {        synchronized (this) {            print(x);            newLine();        }    }    public void println(float x) {        synchronized (this) {            print(x);            newLine();        }    }    public void println(double x) {        synchronized (this) {            print(x);            newLine();        }    }    public void println(char x[]) {        synchronized (this) {            print(x);            newLine();        }    }    public void println(String x) {        synchronized (this) {            print(x);            newLine();        }    }    public void println(Object x) {        String s = String.valueOf(x);        synchronized (this) {            print(s);            newLine();        }    }    /**     * 写入一个格式化的字符串到输出流中     * 这个方法与 out.format(format, args) 一毛一样     */    public PrintStream printf(String format, Object ... args) {        return format(format, args);    }    public PrintStream printf(Locale l, String format, Object ... args) {        return format(l, format, args);    }    public PrintStream format(String format, Object ... args) {        try {            synchronized (this) {                ensureOpen();                if ((formatter == null)                    || (formatter.locale() != Locale.getDefault()))                    formatter = new Formatter((Appendable) this);                formatter.format(Locale.getDefault(), format, args);            }        } catch (InterruptedIOException x) {            Thread.currentThread().interrupt();        } catch (IOException x) {            trouble = true;        }        return this;    }    public PrintStream format(Locale l, String format, Object ... args) {        try {            synchronized (this) {                ensureOpen();                if ((formatter == null)                    || (formatter.locale() != l))                    formatter = new Formatter(this, l);                formatter.format(l, format, args);            }        } catch (InterruptedIOException x) {            Thread.currentThread().interrupt();        } catch (IOException x) {            trouble = true;        }        return this;    }    public PrintStream append(CharSequence csq) {        if (csq == null)            print("null");        else            print(csq.toString());        return this;    }    public PrintStream append(CharSequence csq, int start, int end) {        CharSequence cs = (csq == null ? "null" : csq);        write(cs.subSequence(start, end).toString());        return this;    }    public PrintStream append(char c) {        print(c);        return this;    }}

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 {    /**     * PrintWriter 底层的 Writer     */    protected Writer out;    private final boolean autoFlush;    private boolean trouble = false;    private Formatter formatter;    private PrintStream psOut = null;    private final String lineSeparator;    /**     * 给定 字符集名称,返回字符集对象。     */    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);        }    }    public PrintWriter (Writer out) {        this(out, false);    }    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"));    }    /**     * 还可以包装 OutputStream 呢     */    public PrintWriter(OutputStream out) {        this(out, false);    }    public PrintWriter(OutputStream out, boolean autoFlush) {        this(new BufferedWriter(new OutputStreamWriter(out)), autoFlush);        // save print stream for error propagation        if (out instanceof java.io.PrintStream) {            psOut = (PrintStream) out;        }    }    /**     * 使用默认的编码创建一个 PrintWriter,底层是 BufferedWriter     */    public PrintWriter(String fileName) throws FileNotFoundException {        this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))),             false);    }    /* Private constructor */    private PrintWriter(Charset charset, File file)        throws FileNotFoundException    {        this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset)),             false);    }    public PrintWriter(String fileName, String csn)        throws FileNotFoundException, UnsupportedEncodingException    {        this(toCharset(csn), new File(fileName));    }    public PrintWriter(File file) throws FileNotFoundException {        this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))),             false);    }    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");    }    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;        }    }    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;    }    public void write(int c) {        try {            synchronized (lock) {                ensureOpen();                out.write(c);            }        }        catch (InterruptedIOException x) {            Thread.currentThread().interrupt();        }        catch (IOException x) {            trouble = true;        }    }    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;        }    }    public void write(char buf[]) {        write(buf, 0, buf.length);    }    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;        }    }    public void write(String s) {        write(s, 0, s.length());    }    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;        }    }    /* Methods that do not terminate lines */    public void print(boolean b) {        write(b ? "true" : "false");    }    public void print(char c) {        write(c);    }    public void print(int i) {        write(String.valueOf(i));    }    public void print(long l) {        write(String.valueOf(l));    }    public void print(float f) {        write(String.valueOf(f));    }    public void print(double d) {        write(String.valueOf(d));    }    public void print(char s[]) {        write(s);    }    public void print(String s) {        if (s == null) {            s = "null";        }        write(s);    }    public void print(Object obj) {        write(String.valueOf(obj));    }    /* Methods that do terminate lines */    public void println() {        newLine();    }    public void println(boolean x) {        synchronized (lock) {            print(x);            println();        }    }    public void println(char x) {        synchronized (lock) {            print(x);            println();        }    }    public void println(int x) {        synchronized (lock) {            print(x);            println();        }    }    public void println(long x) {        synchronized (lock) {            print(x);            println();        }    }    public void println(float x) {        synchronized (lock) {            print(x);            println();        }    }    public void println(double x) {        synchronized (lock) {            print(x);            println();        }    }    public void println(char x[]) {        synchronized (lock) {            print(x);            println();        }    }    public void println(String x) {        synchronized (lock) {            print(x);            println();        }    }    public void println(Object x) {        String s = String.valueOf(x);        synchronized (lock) {            print(s);            println();        }    }    public PrintWriter printf(String format, Object ... args) {        return format(format, args);    }    public PrintWriter printf(Locale l, String format, Object ... args) {        return format(l, format, args);    }    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;    }    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;    }    public PrintWriter append(CharSequence csq) {        if (csq == null)            write("null");        else            write(csq.toString());        return this;    }    public PrintWriter append(CharSequence csq, int start, int end) {        CharSequence cs = (csq == null ? "null" : csq);        write(cs.subSequence(start, end).toString());        return this;    }    public PrintWriter append(char c) {        write(c);        return this;    }}
0 0
原创粉丝点击