PrintStreamDataOutputStream 保存的字节数(int,汉字)

xiaoxiao2021-02-28  100

一、测试 一个int 

    第一:建立描述

         1、建立一个文件temp.tmp,存放0--256 的 序数值

         2、使用 

            1》PrintStream 建立

             2》DataOutputStream 建立

       3、结果文件大小不一样

            

   第二:理由:

       例如:共257个数

           1》 PrintStream : 一个数占一个字节。

               左边总数256个字节+右边一个字节=  257个字节,约等于 1KB

          2》DataOutputStream :每一个数占4个字节 。

             左边总数1024个字节+右边4个字节=  1028个字节,约等于 2KB

  第三、内存地址表示:用二维数组表示,目前内存是4G=2^32

         offset :表示目前为止的总数,16累加起来的数,用4字节表示,最大4g多一点点。(1*16,2*16,............)。

        右边:就是16个字节。

   1、  PrintStream  : 1>>offset 用int 表示 

                         

         2>>offset 用16进制 表示

                      

    2、DataOutputStream   存放:

                  

二、测试”严“汉字,java 默认是UTF-8格式保存。

       ”严“:unicode 0x4E25 

               UTF-8 E4 B8 A5

       1、  PrintStream  :每一个字 三个字节*257=771个字节。

            

     2、DataOutputStream :每一个字5个字节   00 03 E4 B8 A5,前面用两字节。加了每一个字符的长度。

            int utflen = 0;                 

                utflen :utf-8 每一字的长度,本例子3,                

                 >>>:无符号右移,高位补0

                 &:位与,相同1得1,其它全0

               实际值: 0000 0000  0000 0000  0000 0000  0000 0011 

                无符号右移动8位:0x 00 00 00 00 取一个字节0x00 00

                无符号右移动0位:就是不移动 ,尾部 取一个 字节 0x 00 03              

             bytearr[count++] = (byte) ((utflen >>> 8) & 0xFF);       bytearr[count++] = (byte) ((utflen >>> 0) & 0xFF);

            发现源码就多了这两句:主要目的就是去掉原来int 的4个字节,取其中最后两个字节。

          

          

 package io;import java.io.BufferedOutputStream;import java.io.DataOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.PrintStream;public class PrintStreamData {public static void main(String[] args) throws Exception {PrintStream dos = new PrintStream(new BufferedOutputStream(new FileOutputStream(new File("temp.tmp"))));for (int i = 0; i < 257; i++)dos.write(i);dos.close();DataOutputStream dos1 = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(new File("temp1.tmp"))));for (int i = 0; i < 257; i++)dos1.writeInt(i);dos1.close();// 必须关闭,东西才到文件中// 严:unicode 0x4E25 //UTF-8 E4 B8 A5PrintStream dos2 = new PrintStream(new BufferedOutputStream(new FileOutputStream(new File("temp2.tmp"))));for (int i = 0; i < 257; i++)dos2.write("严".getBytes());dos2.close();DataOutputStream dos3 = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(new File("temp3.tmp"))));for (int i = 0; i < 257; i++)dos3.writeUTF("严");dos3.close();// 必须关闭,东西才到文件中}}

【资料】 

         http://docs.oracle.com/javase/8/docs/api/java/io/DataInput.html#modified-utf-8

          修改后的UTF-8(Modified UTF-8 (MUTF-8)):

 

转载请注明原文地址: https://www.6miu.com/read-85540.html

最新回复(0)