黑马程序员——Java IO—字节流—PrintStream

来源:互联网 发布:java 正则表达式 筛选 编辑:程序博客网 时间:2024/06/07 09:08
PrintStream是FilterOutputStream的子类,属于装饰流(处理流),用于为被装饰的流提供额外的功能。该类可以提供格式化的输出。

PrintStream的所有方法都不会抛出IOException异常,不抛出并不代表没有出现异常,可以通过checkError方法来查看是否出现了异常。

PrintStream提供了一个自动刷新的功能,当出现如下情况中的任意一种时,将导致自动刷新:
  • 向流中写入一个byte数组之后
  • 调用了println方法
  • 向流中写入了一个换行符或'\n'之后
无论通过PrintStream写入的是什么类型的数据,PrintStream都会先在底层调用String.valueOf(...)方法将其转换成字符串,然后再写入到流中。因为最终写入流中的只能是字节,所以还必须把转换后的字符串按平台默认的字符集编码成对应的字节,再进行写入。
注意:这与直接写入原始数据对应的字节是不同的,下面通过一个小程序来说明一下。

我们把int类型的1写入到流中,由于int占4个字节,所以实际写入时也应写入4个字节;但如果我们把字符'1'写入流中,由于在java中一个字符固定占2个字节,所以实际写入时只会写入2个字节。

package org.lgy.study.io;import java.io.*;import java.util.Arrays;/*javac -d classes "src/org/lgy/study/io/test.java"java org.lgy.study.io.Test*/class Test{public static void main(String[] args){ByteArrayOutputStream baos = null;DataOutputStream dos = null;try{baos = new ByteArrayOutputStream();dos = new DataOutputStream(baos);// 写入int类型的值1,底层会连续写入4个字节dos.writeInt(1);System.out.println(Arrays.toString(baos.toByteArray()));  // [0, 0, 0, 1]// 写入char类型的值'1',底层会连续写入2个字节dos.writeChar('1');System.out.println(Arrays.toString(baos.toByteArray()));  // [0, 0, 0, 1, 0, 49]}catch(IOException e){e.printStackTrace();}finally{if(baos != null){try{baos.close();}catch(IOException e){e.printStackTrace();}}if(dos != null){try{dos.close();}catch(IOException e){e.printStackTrace();}}}}}

PrintStream的构造器:

public PrintStream(File file)            throws FileNotFoundExceptionpublic PrintStream(File file, String csn)            throws FileNotFoundException, UnsupportedEncodingExceptionpublic PrintStream(String fileName)            throws FileNotFoundExceptionpublic PrintStream(String fileName, String csn)            throws FileNotFoundException, UnsupportedEncodingExceptionpublic PrintStream(OutputStream out)public PrintStream(OutputStream out, boolean autoFlush)public PrintStream(OutputStream out, boolean autoFlush, String encoding)            throws UnsupportedEncodingException

PrintSteam有4个构造器可以指定文件,而且还可以指定编码方式,底层实际上根据指定的文件创建了FileOutputStream。

0 0