zoukankan      html  css  js  c++  java
  • 字节流与字符流的区别

     一、前言

    java流在处理上分为字符流和字节流。

    (1)字符流(Writer/Reader)处理的单元为2个字节的Unicode字符,分别操作字符、字符数组或字符串。

    (2)字节流(OutputStream/InputStream)处理单元为1个字节,操作字节和字节数组。

    (3)字节流可用于任何类型

    (4)字符流只能处理字符或者字符串。

    (5)字节流在操作的时候本身是不会用到缓冲区的,是与文件本身直接操作的,所以字节流在操作文件时,即使不关闭资源,文件也能输出。

    (6)字符流在操作的时候是使用到缓冲区的。如果字符流不调用close或flush方法,则不会输出任何内容。 

    所有文件的储存是都是字节(byte)的储存。

        static String path = "/Users/gl/IntelliJProjects/scs/model/src/main/java/com/ys/scs/db/";
        static String printFile = path +  "print.dat";
        static String streamsFile = path +  "stream.dat";
    
        static int a = 5;
        static boolean b = true;
        static char c = 'c';
        static String d = "你好";
    
        public static void main(String[] args) throws Exception {
            writesBytes();
            writesPrint();
        }
    
        public static void writesPrint() throws Exception{
            PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(printFile)));
            writer.print(a);
            writer.print(b);
            writer.print(c);
            writer.print(d);
            writer.close();
        }
    
        public static void writesBytes() throws  Exception{
            DataOutputStream dos =new DataOutputStream(new FileOutputStream(streamsFile));
            dos.writeInt(a);
            dos.writeBoolean(b);
            dos.writeChar(c);
            dos.writeUTF(d);
            dos.writeChars(d);
            dos.writeBytes(d);
        }

    sream.dat

    0000 0005 0100 6300 06E4 BDA0 E5A5 BD4F
    6059 7D60 7D

    分析:

    int变量是四个字节存储, 00 00 00 05 是5

    布尔型变量是一个字节存储,01是true

    char变量是两个字节,00 63 是 c

    剩下的是“你好”的三种写法:

    第一个是00 06 E4 BD A0 E5 A5 BD,前面的00 06是writeUTF加上去的,是字节的数目,后面六个字节是"你好"的UTF编码,每个汉字3个字节
    第二个是4F 60 59 7D   big endian的Unicode编码,每个汉字2个字节
    第三个是60 7D,这是从4F 60 59 7D中分别取得两个汉字的低字节

    UTF-8是一种变长的编码方法,字符长度从1个字节到4个字节不等。最前面的128个字符,只使用1个字节表示,与ASCII码完全相同。

    编号范围                                 字节 
    0x0000 - 0x007F        1
    0x0080 - 0x07FF        2
    0x0800 - 0xFFFF        3
    0x010000 - 0x10FFFF      4

      

    Interface ServletResponse

    To send binary data in a MIME body response, use the ServletOutputStream returned by getOutputStream().

    To send character data, use the PrintWriter object returned by getWriter().

    To mix binary and text data, for example, to create a multipart response, use a ServletOutputStream 

    二、介绍

     


    字符流处理类负责字符流与Java的Unicode字符流之间的转换。

    InputStreamReader和OutputStreamWriter处理字符流和字节流的转换。

    OutputStream

      This abstract class is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes

    and sends them to some sink.

      Applications that need to define a subclass of OutputStream must always provide at least a method that writes one byte of output.

    FileOutputStream

      FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using 

    FileWriter.

    Write

      Abstract class for writing to character streams. The only methods that a subclass must implement are write(char[], int, int), flush(),

    and close(). Most subclasses, however, will override some of the methods defined here in order to provide higher efficiency, additional

    functionality, or both.

    FileWriter

      FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream.

    OutputStreamWriter

      An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using

    a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may

    be accepted.

      Each invocation of a write() method causes the encoding converter to be invoked on the given character(s). The resulting bytes

    are accumulated in a buffer before being written to the underlying output stream. The size of this buffer may be specified, but by default

    it is large enough for most purposes. Note that the characters passed to the write() methods are not buffered.

      For top efficiency, consider wrapping an OutputStreamWriter within a BufferedWriter so as to avoid frequent converter invocations.

    For example: 

    Writer out = new BufferedWriter(new OutputStreamWriter(System.out));

    三、示例

    1.写

    1     public static void main(String[] args) throws IOException {
    2          File f = new File("d:" + File.separator+"test.txt");
    3          OutputStream out = new FileOutputStream(f);
    4          String str = "Hello World";
    5          byte[] b = str.getBytes();  //转换为字节流
    6          out.write(b);
    7          out.close();
    8      }

    2.读

    1      public static void main(String[] args) throws IOException {
    2          File f = new File("d:" + File.separator+"test.txt");
    3          InputStream in=new FileInputStream(f);
    4          byte[] b=new byte[(int) f.length()];
    5          in.read(b);
    6          in.close();
    7          System.out.println(new String(b));    //转换为字符流
    8      }

    参考:

    Node.js: string VS stream

    网络数据流的java处理

     
     
  • 相关阅读:
    flare3d_Material3D_shader3D
    判断2个数组是否相等
    js文件下载几种请求方式,普通请求方式封装
    echarts上下柱形图
    已知数组中的一个元素,求其下标
    判断一个数组是否另一个数组的子集
    js中如何判断一个数组是另一个数组的子集
    高德地图
    php过滤和转义函数
    SQLServer表字段默认值相关信息的获取方法
  • 原文地址:https://www.cnblogs.com/yuyutianxia/p/3832224.html
Copyright © 2011-2022 走看看