Java連載154-IO總結(一)

一、類圖

154.1
154.1
  • 基本上IO可以分爲字節流和字符流

二、字符大小

  • 一般來說一個字母佔用一個字節,一個漢字佔用兩個字節。具體還要看字符編碼,比如說在 UTF-8 編碼下,一個英文字母(不分大小寫)爲一個字節,一箇中文漢字爲三個字節;在 Unicode 編碼中,一個英文字母爲一個字節,一箇中文漢字爲兩個字節。

三、常用方法

InputStream

  • int read() 讀取數據
  • int read(byte[] b, int off, int length) 從第off個字節開始讀取長度爲length的字節,放到數組b中
  • long skip(long n) 跳過指定長度的字節
  • int available() 返回可讀取的字節長度
  • void close() 關閉字節流

OutputStream

  • void write(int b) 寫入一個字節,雖然傳入的是int類型,但是隻會傳入低八位,前24位捨棄
  • void write(byte[] b, int off, int length) 在數組b中,從第off個字節開始,讀取長度爲length的字節
  • void fluhsh() 強制刷新,將緩衝區數據寫入
  • void close() 關閉字節流

Reader

  • int read() 讀取數據
  • int read(char[] b, int off, int length) 從第off個字符開始讀取長度爲length的字符,放到數組b中
  • long skip(long n) 跳過指定長度的字符
  • int ready() 是否可以讀了
  • void close() 關閉字節流

Writer

  • void write(char b) 寫入一個字符
  • void write(byte[] b, int off, int length) 在數組b中,從第off個字節開始,讀取長度爲length的字節
  • void fluhsh() 強制刷新,將緩衝區數據寫入
  • void close() 關閉字節流

四、按照IO流操作的對象來進行分類

154.2
154.2

五、分別舉例

  • 先舉個FileInputStream的列子
package com.newJava;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class D154_InputOutputStream {
 public static void main(String[] args) {
  InputStream is = null;
  String address = "E:\\d05_gitcode\\Java\\newJava\\src\\com\\newJava\\newFile.txt";
  int b;
  try {
   is = new FileInputStream(address);
   while ((b = is.read()) != -1) {  // 可以看出是一個字節一個字節讀取的
    System.out.println((char)b);
   }

  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    is.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
   
 }

}

154.3
154.3
  • 原文 154.4

六、源碼:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章