PrintStream是打印输出流,继承于FilterOutputStream,PrintStream是用来装饰其他输出流,为其他输出流添加功能,方便他们打印出各种数据值表示形式。与其他输出流不同,PrintStream永远不会抛出IOException,它产生的错误会被自身的函数所捕获并设置错误标记,用户可以通过checkError()返回错误标记,查看是否产生IOException。PrintStream提供了自动flush和字符集设置功能,写入的数据会立刻调用flush()函数。
PrintStream主要的函数列表:
PrintStream(OutputStream out)
// 将“输出流out”作为PrintStream的输出流,自动flush,并且采用默认字符集。
PrintStream(OutputStream out, boolean autoFlush)
// 将“输出流out”作为PrintStream的输出流,自动flush,采用charsetName字符集。
PrintStream(OutputStream out, boolean autoFlush, String charsetName)
// 创建file对应的FileOutputStream,然后将该FileOutputStream作为PrintStream的输出流,不自动flush,采用默认字符集。
PrintStream(File file)
// 创建file对应的FileOutputStream,然后将该FileOutputStream作为PrintStream的输出流,不自动flush,采用charsetName字符集。
PrintStream(File file, String charsetName)
// 创建fileName对应的FileOutputStream,然后将该FileOutputStream作为PrintStream的输出流,不自动flush,采用默认字符集。
PrintStream(String fileName)
// 创建fileName对应的FileOutputStream,然后将该FileOutputStream作为PrintStream的输出流,不自动flush,采用charsetName字符集。
PrintStream(String fileName, String charsetName)
// 将“字符c”追加到“PrintStream输出流中”
PrintStream     append(char c)
// 将“字符序列从start(包括)到end(不包括)的全部字符”追加到“PrintStream输出流中”
PrintStream     append(CharSequence charSequence, int start, int end)
// 将“字符序列的全部字符”追加到“PrintStream输出流中”
PrintStream     append(CharSequence charSequence)
// flush“PrintStream输出流缓冲中的数据”,并检查错误
boolean     checkError()
// 关闭“PrintStream输出流”
synchronized void     close()
// flush“PrintStream输出流缓冲中的数据”。
// 例如,PrintStream装饰的是FileOutputStream,则调用flush时会将数据写入到文件中
synchronized void     flush()
// 根据“Locale值(区域属性)”来格式化数据
PrintStream     format(Locale l, String format, Object... args)
// 根据“默认的Locale值(区域属性)”来格式化数据
PrintStream     format(String format, Object... args)
// 将“float数据f对应的字符串”写入到“PrintStream输出流”中,print实际调用的是write函数
void     print(float f)
// 将“double数据d对应的字符串”写入到“PrintStream输出流”中,print实际调用的是write函数
void     print(double d)
// 将“字符串数据str”写入到“PrintStream输出流”中,print实际调用的是write函数
synchronized void     print(String str)
// 将“对象o对应的字符串”写入到“PrintStream输出流”中,print实际调用的是write函数
void     print(Object o)
// 将“字符c对应的字符串”写入到“PrintStream输出流”中,print实际调用的是write函数
void     print(char c)
// 将“字符数组chars对应的字符串”写入到“PrintStream输出流”中,print实际调用的是write函数
void     print(char[] chars)
// 将“long型数据l对应的字符串”写入到“PrintStream输出流”中,print实际调用的是write函数
void     print(long l)
// 将“int数据i对应的字符串”写入到“PrintStream输出流”中,print实际调用的是write函数
void     print(int i)
// 将“boolean数据b对应的字符串”写入到“PrintStream输出流”中,print实际调用的是write函数
void     print(boolean b)
// 将“数据args”根据“Locale值(区域属性)”按照format格式化,并写入到“PrintStream输出流”中
PrintStream     printf(Locale l, String format, Object... args)
// 将“数据args”根据“默认Locale值(区域属性)”按照format格式化,并写入到“PrintStream输出流”中
PrintStream     printf(String format, Object... args)
// 将“换行符”写入到“PrintStream输出流”中,println实际调用的是write函数
void     println()
// 将“float数据对应的字符串+换行符”写入到“PrintStream输出流”中,println实际调用的是write函数
void     println(float f)
// 将“int数据对应的字符串+换行符”写入到“PrintStream输出流”中,println实际调用的是write函数
void     println(int i)
// 将“long数据对应的字符串+换行符”写入到“PrintStream输出流”中,println实际调用的是write函数
void     println(long l)
// 将“对象o对应的字符串+换行符”写入到“PrintStream输出流”中,println实际调用的是write函数
void     println(Object o)
// 将“字符数组chars对应的字符串+换行符”写入到“PrintStream输出流”中,println实际调用的是write函数
void     println(char[] chars)
// 将“字符串str+换行符”写入到“PrintStream输出流”中,println实际调用的是write函数
synchronized void     println(String str)
// 将“字符c对应的字符串+换行符”写入到“PrintStream输出流”中,println实际调用的是write函数
void     println(char c)
// 将“double数据对应的字符串+换行符”写入到“PrintStream输出流”中,println实际调用的是write函数
void     println(double d)
// 将“boolean数据对应的字符串+换行符”写入到“PrintStream输出流”中,println实际调用的是write函数
void     println(boolean b)
// 将数据oneByte写入到“PrintStream输出流”中。oneByte虽然是int类型,但实际只会写入一个字节
synchronized void     write(int oneByte)
// 将“buffer中从offset开始的length个字节”写入到“PrintStream输出流”中。
void     write(byte[] buffer, int offset, int length)
示例程序:
public class PrintStreamTest {

    public static void main(String[] args) {
        testPrintStreamConstrutor1() ;
        // 测试write(), print(), println(), printf()等接口。
        testPrintStreamAPIS() ;
    }
    private static void testPrintStreamConstrutor1() {
        // 0x61对应ASCII码的字母'a',0x62对应ASCII码的字母'b', ...
        final byte[] arr={0x61, 0x62, 0x63, 0x64, 0x65 }; // abced
        try {
            // 创建文件“file.txt”的File对象
            File file = new File("file1.txt");
            // 创建文件对应FileOutputStream
            PrintStream out = new PrintStream(new FileOutputStream(file));
            // 将“字节数组arr”全部写入到输出流中
            out.write(arr);
            // 关闭输出流
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 测试write(), print(), println(), printf()等接口。
    */
    private static void testPrintStreamAPIS() {
        // 0x61对应ASCII码的字母'a',0x62对应ASCII码的字母'b', ...
        final byte[] arr={0x61, 0x62, 0x63, 0x64, 0x65 }; // abced
        try {
            // 创建文件对应FileOutputStream
            PrintStream out = new PrintStream("other.txt");

            // 将字符串“hello PrintStream”+回车符,写入到输出流中
            out.println("hello PrintStream");
            // 将0x41写入到输出流中
            // 0x41对应ASCII码的字母'A',也就是写入字符'A'
            out.write(0x41);
            // 将字符串"65"写入到输出流中。
            // out.print(0x41); 等价于 out.write(String.valueOf(0x41));
            out.print(0x41);
            // 将字符'B'追加到输出流中
            out.append('B');

            // 将"CDE is 5" + 回车  写入到输出流中
            String str = "CDE";
            int num = 5;
            out.printf("%s is %d\n", str, num);

            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
运行结果:
file1.txt文件中为: abcde
other.txt文件中为:
hello PrintStream
A65BCDE is 5

基于JDK8的PrintStream的源码:
is.charOut = new OutputStreamWriter(this);
        this.textOut = new BufferedWriter(charOut);
    }
    //out输出流,自动autoFlash,charset字符集
    private PrintStream(boolean autoFlush, OutputStream out, Charset charset) {
        super(out);
        this.autoFlush = autoFlush;
        this.charOut = new OutputStreamWriter(this, charset);
        this.textOut = new BufferedWriter(charOut);
    }

    /* Variant of the private constructor so that the given charset name
     * can be verified before evaluating the OutputStream argument. Used
     * by constructors creating a FileOutputStream that also take a
     * charset name.
     */
    private PrintStream(boolean autoFlush, Charset charset, OutputStream out) throws UnsupportedEncodingException
    {
        this(autoFlush, out, charset);
    }
    //out输出流,不会自动flush,m默认字符集
    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));
    }
    //将FileOutputStream作为输入流,不自动flush,默认字符集
    public PrintStream(String fileName) throws FileNotFoundException {
        this(false, new FileOutputStream(fileName));
    }
    //FileOutputStream输出流,不自动flush,csn字符集
    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));
    }
    //FileOutputStream输出流,不自动flush,默认字符集
    public PrintStream(File file) throws FileNotFoundException {
        this(false, new FileOutputStream(file));
    }
    //FileOutputStream输出流,csn字符集,不自动flush
    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");
    }
    //刷新
    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();
                }
                catch (IOException x) {
                    trouble = true;
                }
                textOut = null;
                charOut = null;
                out = null;
            }
        }
    }
    //flush PrintStream输出流缓冲中数据,并检查错误
    public boolean checkError() {
        if (out != null)
            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
     */

    //将数据b写入到PrintStream中,b虽然是int类型,但实际只会写入一个字节
    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)
                    out.flush();
             }
        }
        catch (InterruptedIOException x) {
            Thread.currentThread().interrupt();
        }
        catch (IOException x) {
            trouble = true;
        }
    }

    /*
     * The following private methods on the text- and character-output streams
     * always flush the stream buffers, so that writes to the underlying byte
     * stream occur as promptly as with the original PrintStream.
     */
    //将b中的全部数据写入到PrintStream中
    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;
        }
    }
    //String写到PrintStream中
    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;
        }
    }
    //换行符写到PrintStream中
    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 */

    //将b对应的字符串写到PrintStream中
    public void print(boolean b) {
        write(b ? "true" : "false");
    }

    //最后都是转化为String

    //字符串
    public void print(char c) {
        write(String.valueOf(c));
    }
    //int类型
    public void print(int i) {
        write(String.valueOf(i));
    }
    //long类型
    public void print(long l) {
        write(String.valueOf(l));
    }
    //float
    public void print(float f) {
        write(String.valueOf(f));
    }
    //double
    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();
    }
    //boolean+换行
    public void println(boolean x) {
        synchronized (this) {
            print(x);
            newLine();
        }
    }
    //char+换行
    public void println(char x) {
        synchronized (this) {
            print(x);
            newLine();
        }
    }
    //int+换行
    public void println(int x) {
        synchronized (this) {
            print(x);
            newLine();
        }
    }
    //long+换行
    public void println(long x) {
        synchronized (this) {
            print(x);
            newLine();
        }
    }
    //float+换行
    public void println(float x) {
        synchronized (this) {
            print(x);
            newLine();
        }
    }
    //double+换行
    public void println(double x) {
        synchronized (this) {
            print(x);
            newLine();
        }
    }
    //char数组+换行
    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();
        }
    }

    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);
    }
    // 将“数据args”根据“默认Locale值(区域属性)”按照format格式化,并写入到“PrintStream输出流”中
    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;
    }

}

Java-IO之PrintStream(打印输出流)的更多相关文章

  1. java io系列16之 PrintStream(打印输出流)详解

    本章介绍PrintStream以及 它与DataOutputStream的区别.我们先对PrintStream有个大致认识,然后再深入学习它的源码,最后通过示例加深对它的了解. 转载请注明出处:htt ...

  2. Java中PrintStream(打印输出流)

    Java中PrintStream(打印输出流)   PrintStream 是打印输出流,它继承于FilterOutputStream. PrintStream 是用来装饰其它输出流.它能为其他输出流 ...

  3. java的PrintStream(打印输出流)详解(java_io)

    java的PrintStream(打印输出流)详解(java_io) 本章介绍PrintStream以及 它与DataOutputStream的区别.我们先对PrintStream有个大致认识,然后再 ...

  4. Java Io(数据输入输出流)

    Java Io 字节流中的DataInputStream 和 DataOutputStream,使用流更加方便,是流的一个扩展,更方便读取int, long,字符等类型数据. 事例代码如下: pack ...

  5. Java Io 流(输入输出流)

    IO流,也就是输入和输出流,可分为字节流和字符流. 1. 字节流 (1). InputStream 输入流,用于读取文件 输入流常用API: inputStream.read()  读取一个字节 in ...

  6. java IO流 之 字节输出流 OutputString()

    Java学习重点之一:OutputStream 字节输出流的使用 FileOutPutStream:子类,写出数据的通道 步骤: 1.获取目标文件 2.创建通道(如果原来没有目标文件,则会自动创建一个 ...

  7. 系统学习 Java IO (一)----输入流和输出流 InputStream/OutputStream

    目录:系统学习 Java IO ---- 目录,概览 InputStream 是Java IO API中所有输入流的父类. 表示有序的字节流,换句话说,可以将 InputStream 中的数据作为有序 ...

  8. 缓冲字符流 java.io.BufferedWriter ,java.io.BufferedReader,缓冲字符输出流:PrintWriter

    package seday07; import java.io.IOException;import java.io.PrintWriter; /*** @author xingsir * 缓冲字符流 ...

  9. Java IO流之打印流与标准流

    一.打印流 1.1打印流特点与构造方法 1)PrintStream和PrintWriter类都提供了一系列重载的print和println方法来输出各种类型的数据. 2)PrintStream和Pri ...

  10. java ->IO流_打印流

    打印流的概述 打印流添加输出数据的功能,使它们能够方便地打印各种数据值表示形式. 打印流根据流的分类: 永远不会抛出IO异常 l  字节打印流  PrintStream l  字符打印流  Print ...

随机推荐

  1. 在Cisco Catalyst 3750端口做策略限速 QOS

    今天任务是在3750上限制端口的速率,本来以为是很简单的事,speed命令搞定,敲进去才知道speed命令只能叫端口速率改成10M或100M,也就是说只能起到端口高低速率的切换功能,不能自定义速率,后 ...

  2. RedHatEnterpriseLinuxServerRelease7.3上配置vsftp服务器

    1.vsftpd 服务启停相关命令 systemctl start vsftpd systemctl stop vsftpd systemctl restart vsftpd 2.配置文件/etc/v ...

  3. ftp传二进制文件时一定要用二进制模式,否则内容会有变化,造成后处理莫名其妙的错误,还以为传输前后内容一致,其实已变化。

    ftp传二进制文件时一定要用二进制模式,否则内容会有变化,造成后处理莫名其妙的错误,还以为传输前后内容一致,其实已变化.

  4. LintCode题解之斐波纳契数列

    直接使用递归的方法会导致TLE,加个缓存就好了: public class Solution { private Integer[] buff = new Integer[1000]; /* * @p ...

  5. sorted函数返回一个新的列表就安全了吗?

    arr=[[1,2,3],[4,2,3],[5,2,3]] x2=sorted(arr) print 'sorted',x2 print '-'*20 for ar in arr: ar.append ...

  6. 集群技术(三)MySQL集群深度解析

    什么是MySQL集群 MySQL集群是一个无共享的(shared-nothing).分布式节点架构的存储方案,其目的是提供容错性和高性能. 数据更新使用读已提交隔离级别(read-committedi ...

  7. Linux Mint 17一周使用体验

    1 Win7下安装Mint双系统 Linux Mint支持直接从Win7硬盘引导安装,非常方便,不用制作U盘引导,更不用刻盘安装了.Mint有Cinnamon和Mate两种桌面,听说Mate更加简洁节 ...

  8. Git之(五)远程管理

    开篇就提到过,Git是一个分布式版本管理系统.但是到现在为止,我们所有的演练都是在本地Git仓库.如果想与他人合作,还需要一个远程的 Git 仓库.尽管技术上可以从个人的仓库里推送和拉取修改内容,但我 ...

  9. springMVC源码分析--RequestMappingHandlerAdapter(五)

    上一篇博客springMVC源码分析--HandlerAdapter(一)中我们主要介绍了一下HandlerAdapter接口相关的内容,实现类及其在DispatcherServlet中执行的顺序,接 ...

  10. springMVC源码分析--ControllerBeanNameHandlerMapping(八)

    在上一篇博客springMVC源码分析--AbstractControllerUrlHandlerMapping(六)中我们介绍到AbstractControllerUrlHandlerMapping ...