摘要:
Java 流在处理上分为字符流和字节流。字符流处理的单元为 2 个字节的 Unicode 字符,分别操作字符、字符数组或字符串,而字节流处理单元为 1 个字节,操作字节和字节数组。
Java 内用 Unicode 编码存储字符,字符流处理类负责将外部的其他编码的字符流和 java 内 Unicode 字符流之间的转换。而类 InputStreamReader 和 OutputStreamWriter 处理字符流和字节流的转换。字符流(一次可以处理一个缓冲区)一次操作比字节流(一次一个字节)效率高。
(一)以字节为导向的 Stream------InputStream/OutputStream
InputStream 和 OutputStream 是两个 abstact 类,对于字节为导向的 stream 都扩展这两个基类;
1、 InputStream
基类InputStream:
构造方法:
InputStream() 创建一个输入的stream流
方法:
available():返回stream中的可读字节数,inputstream类中的这个方法始终返回的是0,这个方法需要子类去实现。
close():关闭stream方法,这个是每次在用完流之后必须调用的方法。
read():方法是读取一个byte字节,但是返回的是int。
read(byte[]):一次性读取内容到缓冲字节数组
read(byte[],int,int):从数据流中的哪个位置offset开始读长度为len的内容到缓冲字节数组
skip(long):从stream中跳过long类型参数个位置
以上的方法都是很简单理解的,这里就不写代码介绍了。
下面还有三个方法:
mark(int):用于标记stream的作用
markSupported():返回的是boolean类型,因为不是所有的stream都可以调用mark方法的,这个方法就是用来判断stream是否可以调用mark方法和reset方法
reset():这个方法和mark方法一起使用的,让stream回到mark的位置。
上面说的可能抽象了点,下面就用代码来解释一下吧:
package com.io.demo;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class InputStreamTest { public static void main(String[] args) throws IOException { writeToFile(); readFromFile(); } private static void readFromFile() { InputStream inputStream = null; try { inputStream = new BufferedInputStream(new FileInputStream(new File("test.txt"))); // 判断该输入流是否支持mark操作 if (!inputStream.markSupported()) { System.out.println("mark/reset not supported!"); return; } int ch; int count = 0; boolean marked = false; while ((ch = inputStream.read()) != -1) { System.out.print("." + ch); if ((ch == 4) && !marked) { // 在4的地方标记位置 inputStream.mark(10); marked = true; } if (ch == 8 && count < 2) { // 重设位置到4 inputStream.reset(); count++; } } } catch (Exception e) { e.printStackTrace(); } finally { try { inputStream.close(); } catch (Exception e) { e.printStackTrace(); } } } private static void writeToFile() { OutputStream output = null; try { output = new BufferedOutputStream(new FileOutputStream(new File("test.txt"))); byte[] b = new byte[20]; for (int i = 0; i < 20; i++) b[i] = (byte) i; // 写入从0到19的20个字节到文件中 output.write(b); } catch (IOException e) { e.printStackTrace(); } finally { try { output.close(); } catch (IOException e) { e.printStackTrace(); }