这篇文章主要介绍了java中IO流有哪些,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
以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[]) 方法源码
假设现在你要写一个程序以计算一个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中读写文件的示意图
转换流实现了在指定的编码方式下进行字节编码和字符编码的转换。转换流如果直接从硬盘一次一个字节读取的转换流效率也很低,所以转换流一般都是基于字节缓冲流的。转换流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()
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做对比)
感谢你能够认真阅读完这篇文章,希望小编分享的“java中IO流有哪些”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。