JAVA OutputStreamWriter转换流,蓝牙打印小票

前言

之前项目需要做打印小票的功能,实现上采用蓝牙连接打印机,蓝牙在上一篇已经介绍了,只是查找与连接的API调用。主要难点是通过OutPutStreamWriter进行小票的排版然后写入到打印机进行打印。因此,本篇主要讲解的也就是转换流OutputStreamWriter。

我们知道,在序列化存储文件时,通过输入输出流将file从内存中存储到本地。而字符数据是通过OutputStreamWriter变为字节流才能保存在文件里的,读取时需要将读入的字节流通过InputStreamReader变为字符流。

(蓝牙连接发生文件、打印小票的开源demo)

GitHub:https://github.com/aiyangtianci/BluetoothAPP 

一、概述

 OutputStreamWriter是Writer的子类,将输出的字符流变为字节流,即将一个字符流的输出对象变为字节流输出对象。使用指定的字符集将写入其中的字符编码为字节。它使用的字符集可以通过名称指定,也可以明确指定,或者可以接受平台的默认字符集。当调用write()方法都会导致在给定字符上调用编码转换器。生成的字节在写入底层输出流之前在缓冲区中累积。可以指定此缓冲区的大小,但默认情况下,它足够大,可用于大多数用途。

二、构造函数

   private final StreamEncoder se;
   //out:输出流
   public OutputStreamWriter(OutputStream out) {
        super(out);
        try {
            se = StreamEncoder.forOutputStreamWriter(out, this, (String)null);
        } catch (UnsupportedEncodingException e) {
            throw new Error(e);
        }
    }
   //charsetName:指定的字符编码
   public OutputStreamWriter(OutputStream out, String charsetName)
        throws UnsupportedEncodingException
   {
        super(out);
        if (charsetName == null)
            throw new NullPointerException("charsetName");
        se = StreamEncoder.forOutputStreamWriter(out, this, charsetName);
   }

三、OutputStreamWriter extends Writer

1、写入一个字符到流中:调用StreamEncoder的write(int c)方法

    public void write(int c) throws IOException {
        se.write(c);
    }


2、写入字符数组的一部分到流中:调用StreamEncoder的write(char cbuf[], int off, int len)方法

public void write(char cbuf[], int off, int len) throws IOException {
        se.write(cbuf, off, len);
    }

3、写入字符串的一部分到流中:调用StreamEncoder的write(String str, int off, int len)方法

  public void write(String str, int off, int len) throws IOException {
        se.write(str, off, len);
    }

4、刷新流中的数据:调用StreamEncoder的flush()方法 

public void flush() throws IOException {
        se.flush();
    }

5、关闭流但是先刷新流:即该流必须要先调用flush方法然后再调用close方法

    public void close() throws IOException {
        se.close();
    }

四、原理总结

字符的输出需要通过字符流来操作,但是本质上来说,最后还是通过字节流输出到计算机上进行存储的,因此OutputStreamWriter流的作用就是利用字节流作为底层输出流然后构建字符输出流,字符输出流输出字符到流中,然后通过指定的字符集把流中的字符编码成字节输出到字节流中,其作用就是一个桥梁,使得双方链接起来。

  OutputStreamWriter中存在一个字节缓冲区,用于存储每次输出的字符编码后的字节,然后待字符输出流输出完毕一次性的将存储的字节全部输出给底层的字节输出流


参考链接:https://blog.csdn.net/ai_bao_zi/article/details/81168420

发布了153 篇原创文章 · 获赞 755 · 访问量 100万+

猜你喜欢

转载自blog.csdn.net/csdn_aiyang/article/details/100102855