一、类图

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

六、源码:

posted on 2021-12-22 00:36  心悦君兮君不知-睿  阅读(108)  评论(0编辑  收藏  举报