字節流與字符流的區別


 一、前言

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處理

 

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM