浅析java中的IO流

在java中IO类很庞大,初学的时候觉得傻傻分不清楚。其实java流归根结底的原理是普通字节流,字节缓冲流,转换流。最基础的是普通字节流,即从硬盘读取字节写入到内存中,但在实际使用中又发现一些特殊的需求,所以java语言的设计者这引入了字节缓冲流和转换流。所有的java IO类对IO的处理都是基于这三种流中的一种或多种;在介绍完三种流的概念之后,会对IO流的部分java类做介绍。

1.普通字节流

以FileInputStream为例子。FileInputStream的硬盘读取方式分为两种,一次读取一个字节和一次读取一个字节数组。字节数组的大小不同,实际IO耗时也不同,图1为示例代码,图3展示了图1代码中读写耗时随字节数组大小的变化趋势。随着字节数组的增大,读写耗时减小,主要是硬盘寻道时间(seek time)和旋转时间(rotational latency)的减少。在硬盘读写耗时很长时,内存读写的耗时相比硬盘读写可以忽略,硬盘读写的耗时分为寻道时间(seek time)、旋转时间(rotational latency)和传输时间(transfer time),传输时间相对于寻道时间和旋转时间(寻道时间和旋转时间后合并称为寻址时间)可以忽略【1】。硬盘的寻址时间在一个块中的第一个字节耗时长,一个块中的其余字节可以忽略。当字节数组增大时(从32增加到1024*16 byte),寻址一个块中的第一个字节的场景线性减少,寻址时间也线性减少,因此IO耗时呈线性减少趋势。当字节数组大小继续增大(从1024 * 8增加到1024 * 1024 * 16),此时寻址时间已降到很低,相比传输时间可以忽略时,IO耗时的变化趋于平稳。当字节数组大小继续增大时,读写耗时又出现增大的趋势,这个我还没找到原因。当在数组较大(大于1024 *1024 *4)时,read(byte[])方法中除去读写之外也会有其它耗时,测试代码如图2,测试数据如图3附表,这个机制我还不清楚(可能需要深入了解jvm的底层实现了),图3中在计算读写耗时时应减去这部分时间。

public class Demo01_Copy {

	public static void main(String[] args) throws IOException {
		File src = new File ("e:\\foxit_Offline_FoxitInst.exe");
		File dest = new File("e:\\ithema\\foxit_Offline_FoxitInst.exe");

		byte[] bytes = new byte[1024*128];//调整字节数组的大小,看IO耗时的变化
		long time1 = System.currentTimeMillis();
		copyFile2(src,dest,bytes);
		long time2 = System.currentTimeMillis();
		System.out.println(time2 -time1);
	}
	
	public static void copyFile2(File src,File dest,byte[] bytes) throws IOException{
		InputStream in = new FileInputStream(src);
		OutputStream os = new FileOutputStream(dest);
		
		int len = 0;
		while((len = in.read(bytes))!=-1){
			os.write(bytes,0,len);
		}
		in.close();
		os.close();
	}
}

图1 通过FileInputStream一次读取一个字节数组

public class Demo02_Copy {
    public static void main(String[] args) throws IOException {
        File src = new File ("e:\\1.txt");
        File dest = new File("e:\\ithema\\1.txt");

        byte[] bytes = new byte[1024*128];//调整字节数组的大小,看IO耗时的变化
        long time1 = System.currentTimeMillis();
        copyFile2(src,dest,bytes);
        long time2 = System.currentTimeMillis();
        System.out.println(time2 -time1);
    }

    public static void copyFile2(File src,File dest,byte[] bytes) throws IOException{
        InputStream in = new FileInputStream(src);
        OutputStream os = new FileOutputStream(dest);

        int len = 0;
        while((len = in.read(bytes))!=-1){
            os.write(bytes,0,len);
        }
        in.close();
        os.close();
    }
}

图 2 测试除硬盘内存读写外的其它耗时(1.txt文件为空)

图3 当字节数组大小变化,读写总耗时的变化趋势(折线图数据来源于表格中蓝色背景填充的数据)

当数组大小从32逐渐增大到1024*16byte时,IO耗时呈线性减少,这基于FileInputStream的read(byte[])实现。read(byte[])的源码如图4所示,read(byte b[])是一个本地方法,它保证了硬盘的寻址时间在读取一个数组大小的字节块的第一个字节耗时较长,字节块的其余字节可以忽略。而相对于read()方法,一个字节一个字节读取,每读取一个字节都要重新进行硬盘寻址。

public class FileInputStream extends InputStream
{
    public int read(byte b[]) throws IOException {
        return readBytes(b, 0, b.length);
    }
    
     /**
     * Reads a subarray as a sequence of bytes.
     * @param b the data to be written
     * @param off the start offset in the data
     * @param len the number of bytes that are written
     * @exception IOException If an I/O error has occurred.
     */
    private native int readBytes(byte b[], int off, int len) throws IOException;
}

图4 FileInputStream 的 read(byte[]) 方法源码

2.字节缓冲流

假设现在你要写一个程序以计算一个text文件的行数。一种方法是使用read()方法从硬盘中一次读取1个字节到内存中,并检查该字节是不是换行符“\n”【2】。这种方法已被证明是低效的。

更好的方法是使用字节缓冲流,先将字节从硬盘一次读取一个缓冲区大小的字节到内存中的读缓冲区,然后在从读缓冲区中一次读取一个字节。在逐字节读取读取缓冲区时,检查字节是不是换行符’\n’。字节缓冲流BufferedInputStream的源码如图5所示,先从硬盘读取一个缓冲大小的字节块到缓冲区,然后逐个读取缓冲区的字节;当缓冲区的字节读取完毕后,在调用fill()方法填充缓冲区。字节缓冲流BufferedInputStream的缓冲区大小为8192。图6中对比了字节缓冲流和普通字节流的读写效率;字节缓冲流的读耗时仅为8ms,而没有缓冲区的普通字节流的耗时为567ms。图7中展示了图6中字节缓冲流读写文件的示意图。

public class BufferedInputStream extends FilterInputStream {
    private static int DEFAULT_BUFFER_SIZE = 8192;
    
	public synchronized int read() throws IOException {
        //当缓冲区的字节已被读取完毕后,调用fill()方法从硬盘读取字节块填充缓冲区;
        if (pos >= count) {
            fill();
            if (pos >= count)
                return -1;
        }
        //返回缓冲区的一个字节
        return getBufIfOpen()[pos++] & 0xff;
    }

	private void fill() throws IOException {
        byte[] buffer = getBufIfOpen();
        //初始定义int markpos = -1;
        if (markpos < 0)
            pos = 0;            /* no mark: throw away the buffer */
        else if (pos >= buffer.length)  /* no room left in buffer */
            if (markpos > 0) {  /* can throw away early part of the buffer */
                int sz = pos - markpos;
                System.arraycopy(buffer, markpos, buffer, 0, sz);
                pos = sz;
                markpos = 0;
            } else if (buffer.length >= marklimit) {
                markpos = -1;   /* buffer got too big, invalidate mark */
                pos = 0;        /* drop buffer contents */
            } else if (buffer.length >= MAX_BUFFER_SIZE) {
                throw new OutOfMemoryError("Required array size too large");
            } else {            /* grow buffer */
                int nsz = (pos <= MAX_BUFFER_SIZE - pos) ?
                        pos * 2 : MAX_BUFFER_SIZE;
                if (nsz > marklimit)
                    nsz = marklimit;
                byte nbuf[] = new byte[nsz];
                System.arraycopy(buffer, 0, nbuf, 0, pos);
                if (!bufUpdater.compareAndSet(this, buffer, nbuf)) {
                    // Can't replace buf if there was an async close.
                    // Note: This would need to be changed if fill()
                    // is ever made accessible to multiple threads.
                    // But for now, the only way CAS can fail is via close.
                    // assert buf == null;
                    throw new IOException("Stream closed");
                }
                buffer = nbuf;
            }
        count = pos;
        //从硬盘读取一个缓冲区大小的块到缓冲区
        int n = getInIfOpen().read(buffer, pos, buffer.length - pos);
        if (n > 0)
            count = n + pos;
    }
}

图5 BufferedInputStream的read()方法源码

public class Demo03_Copy {

	public static void main(String[] args) throws IOException {
		File src = new File ("e:\\settings.xml");
		File dest = new File("e:\\ithema\\settings.xml");

		byte[] bytes = new byte[1024*128];
		long time1 = System.currentTimeMillis();
		//耗时:567 ms
        //copyFile1(src,dest);
		//耗时:8 ms
		copyFile3(src,dest);
		long time2 = System.currentTimeMillis();
		System.out.println(time2 -time1);
	}

    //使用普通字节流
	public static void copyFile1(File src,File dest) throws IOException{
		InputStream in = new FileInputStream(src);
		OutputStream os = new FileOutputStream(dest);
		int len = 0;
		int lineSum = 1;
		while((len = in.read())!= -1){
			if(len == '\n'){
				lineSum++;
			}
			os.write(len);
		}
		System.out.println("lineSum:"+lineSum);
		in.close();
		os.close();
	}
	
    //使用字节缓冲流
	public static void copyFile3(File src,File dest) throws IOException{
		
		InputStream in = new BufferedInputStream(new FileInputStream(src));
		OutputStream os = new BufferedOutputStream(new FileOutputStream(dest));
		
		int len = 0;
		int lineSum = 1;
		while((len = in.read())!=-1){
			if(len == '\n'){
				lineSum ++;
			}
			os.write(len);
		}
		System.out.println("lineSum:"+lineSum);
		in.close();
		os.close();
	}
}

图6 字节缓冲流和普通字节流的读写效率对比

图7 使用字节缓冲流在图6中读写文件的示意图

3.转换流

转换流实现了在指定的编码方式下进行字节编码和字符编码的转换。转换流如果直接从硬盘一次一个字节读取的转换流效率也很低,所以转换流一般都是基于字节缓冲流的。转换流InputStreamReader的使用如图8所示,图中代码底层的执行流程图如图9所示。InputStreamReader 的源码解析图如图10所示,转码的关键代码如图11所示。如图11,一个字符的字符编码所占字节个数固定为2个字节,但一个字符的字符编码经过转换流按UTF-8格式转换为字节编码后,字节编码所占字节个数为1~4个。

public class Demo01_InputStreamReader {
	public static void main(String[] args) throws IOException {
		readUTF();
	}
    
    //一次读取一个字符
	public static void readUTF() throws IOException{
		InputStreamReader isr = new InputStreamReader(new FileInputStream("e:\\2.txt"),"UTF-8");
		int ch = 0;
		while((ch = isr.read())!=-1){
			System.out.println((char)ch);
		}
		isr.close();
	}
}

图8 使用转换流InputStreamReader一次读取一个字符

图9 InputStreamReader在read()时的底层流程图(文件中的字节编码可通过FileInputStream读取查看)

图10 InputStreamReader的read()源码解析图

class UTF_8 extends Unicode{
    private CoderResult decodeArrayLoop(ByteBuffer paramByteBuffer, CharBuffer paramCharBuffer)
    {
      byte[] arrayOfByte = paramByteBuffer.array();
      int i = paramByteBuffer.arrayOffset() + paramByteBuffer.position();
      int j = paramByteBuffer.arrayOffset() + paramByteBuffer.limit();
      char[] arrayOfChar = paramCharBuffer.array();
      int k = paramCharBuffer.arrayOffset() + paramCharBuffer.position();
      int m = paramCharBuffer.arrayOffset() + paramCharBuffer.limit();
      int n = k + Math.min(j - i, m - k);
      while ((k < n) && (arrayOfByte[i] >= 0))
        arrayOfChar[(k++)] = (char)arrayOfByte[(i++)];
      while (i < j)
      {
        int i1 = arrayOfByte[i];
        if (i1 >= 0)
        {
          if (k >= m)
            return xflow(paramByteBuffer, i, j, paramCharBuffer, k, 1);
          arrayOfChar[(k++)] = (char)i1;
          i++;
        }
        else
        {
          int i2;
          if ((i1 >> 5 == -2) && ((i1 & 0x1E) != 0))
          {
            if ((j - i < 2) || (k >= m))
              return xflow(paramByteBuffer, i, j, paramCharBuffer, k, 2);
            i2 = arrayOfByte[(i + 1)];
            if (isNotContinuation(i2))
              return malformedForLength(paramByteBuffer, i, paramCharBuffer, k, 1);
            arrayOfChar[(k++)] = (char)(i1 << 6 ^ i2 ^ 0xF80);
            i += 2;
          }
          else
          {
            int i3;
            int i4;
            if (i1 >> 4 == -2)
            {
              i2 = j - i;
              if ((i2 < 3) || (k >= m))
              {
                if ((i2 > 1) && (isMalformed3_2(i1, arrayOfByte[(i + 1)])))
                  return malformedForLength(paramByteBuffer, i, paramCharBuffer, k, 1);
                return xflow(paramByteBuffer, i, j, paramCharBuffer, k, 3);
              }
              i3 = arrayOfByte[(i + 1)];
              i4 = arrayOfByte[(i + 2)];
              if (isMalformed3(i1, i3, i4))
                return malformed(paramByteBuffer, i, paramCharBuffer, k, 3);
              char c = (char)(i1 << 12 ^ i3 << 6 ^ (i4 ^ 0xFFFE1F80));
              if (Character.isSurrogate(c))
                return malformedForLength(paramByteBuffer, i, paramCharBuffer, k, 3);
              arrayOfChar[(k++)] = c;
              i += 3;
            }
            else if (i1 >> 3 == -2)
            {
              i2 = j - i;
              if ((i2 < 4) || (m - k < 2))
              {
                i1 &= 255;
                if ((i1 > 244) || ((i2 > 1) && (isMalformed4_2(i1, arrayOfByte[(i + 1)] & 0xFF))))
                  return malformedForLength(paramByteBuffer, i, paramCharBuffer, k, 1);
                if ((i2 > 2) && (isMalformed4_3(arrayOfByte[(i + 2)])))
                  return malformedForLength(paramByteBuffer, i, paramCharBuffer, k, 2);
                return xflow(paramByteBuffer, i, j, paramCharBuffer, k, 4);
              }
              i3 = arrayOfByte[(i + 1)];
              i4 = arrayOfByte[(i + 2)];
              int i5 = arrayOfByte[(i + 3)];
              int i6 = i1 << 18 ^ i3 << 12 ^ i4 << 6 ^ (i5 ^ 0x381F80);
              if ((isMalformed4(i3, i4, i5)) || (!Character.isSupplementaryCodePoint(i6)))
                return malformed(paramByteBuffer, i, paramCharBuffer, k, 4);
              arrayOfChar[(k++)] = Character.highSurrogate(i6);
              arrayOfChar[(k++)] = Character.lowSurrogate(i6);
              i += 4;
            }
            else
            {
              return malformed(paramByteBuffer, i, paramCharBuffer, k, 1);
            }
          }
        }
      }
      return xflow(paramByteBuffer, i, j, paramCharBuffer, k, 0);
    }
}

图11 UTF_8中将字节编码解码为字符编码的方法decodeArrayLoop()

4.常用的IO类FileReader和BufferedReader

FileReader(String fileName)和InputStreamReader(new FileInputStream(String fileName))是等价的,如图12所示,具体实现参见第3节。BufferedReader的实现与FileReader不同,它们的性能对比如图13所示。图14展示了BufferedReader的使用,这为了和图7中InputStreamReader(new FileInputStream(String fileName))的使用做对比。图14中代码底层的执行流程图如图15所示。BufferedReader的方法read()的源码解析图如图16所示。BufferedReader和FileReader在字符编码和字节编码的转换时都调用了CharsetDecoder.decode()方法;不同的是BufferedReader一次转换了8192个字符(图15),而FileReader一次只转换了2个字符(图9)。但由于BufferedReader和FileReader的字节缓冲区大小于均为8192个字节,因此BufferedReader与FileReader效率相差不大。

public class FileReader extends InputStreamReader {
    public FileReader(String fileName) throws FileNotFoundException {
        super(new FileInputStream(fileName));
    }
}

图12 FileReader(String filePath)的构造方法

public class Demo01_Copy {

	public static void main(String[] args) throws IOException {
		File src = new File ("e:\\foxit_Offline_FoxitInst.exe");
		File dest = new File("e:\\ithema\\foxit_Offline_FoxitInst.exe");

		long time1 = System.currentTimeMillis();
        //耗时:3801 ms
		//copyFile5(src,dest,bytes);
		//耗时:2938 ms
		copyFile6(src,dest);
		long time2 = System.currentTimeMillis();
		System.out.println(time2 -time1);
	}


	public static void copyFile5(File src ,File dest) throws IOException {
		FileReader fr = new FileReader(src);
		FileWriter fw = new FileWriter(dest);
		int len = 0;
		while((len=fr.read())!=-1){
			fw.write(len);
		}
		fr.close();
		fw.close();
	}

	public static void copyFile6(File src,File dest) throws IOException{
		BufferedReader br = new BufferedReader(new FileReader(src));
		BufferedWriter bw = new BufferedWriter(new FileWriter(dest));
		int len = 0;
		while((len=br.read())!=-1){
			bw.write(len);
		}
		br.close();
		bw.close();
	}
}

图13 FileReader和BufferedReader的性能对比

public class Demo01_BufferedReader {
	public static void main(String[] args) throws IOException {
		readUTF();
	}
    
    //一次读取一个字符
	public static void readUTF() throws IOException{
		BufferedReader br = new BufferedReader(
            new InputStreamReader(new FileInputStream("e:\\2.txt"),"UTF-8"));
		int ch = 0;
		while((ch = br.read())!=-1){
			System.out.println((char)ch);
		}
		br.close();
	}
}

图14 使用BufferedReader一次读取一个字符(与图7做对比)

图15 BufferedReader在read()时的底层流程图(与图8做对比)

图16 BufferedReader的read()源码解析图(与图9做对比)

5.总结

普通字节流是基础,是最简单高效的流。如果没有特殊的需求,只是高效的进行文件读写,选择合适的字节数组大小,一次从硬盘读取一个字节数组大小的字节块,其效率是最高的。

字节缓冲流是为行数统计,按行读取等特殊需求而设计的。相比于直接从硬盘一次读取一个字节;先从硬盘一次读取一个缓冲区大小的字节块到缓冲区(位于内存),再从缓冲区一个字节一个字节的读取并判断是不是行末尾(’\n’)的效率更高。

转换流实现了在指定的编码方式下进行字节编码和字符编码的转换。转换流如果直接从硬盘一次一个字节读取的转换流效率也很低,所以转换流一般都是基于字节缓冲流的。

参考资料:

【1】Computer Systems A Programmers Perspective.3rd->Section 6.1 Storage Technologies->Disk Operation;

【2】Computer Systems A Programmers Perspective.3rd->Section 10.5.2 Rio Buffered Input Functions;

附件:

文中测试用的文件1.txt,2.txt,foxit_Offline_FoxitInst.exe,settings.xml