java.io.InputStream优化
【原创】java.io.InputStream优化今天无聊看java源码时发现 java.io.InputStream类用于移动文件指针的skip()
【原创】java.io.InputStream优化
今天无聊看java源码时发现 java.io.InputStream类用于移动文件指针的skip()方法可以再优化一下:
源码:
public long skip(long n) throws IOException {long remaining = n;int nr;if (skipBuffer == null) skipBuffer = new byte[SKIP_BUFFER_SIZE]; byte[] localSkipBuffer = skipBuffer;if (n <= 0) { return 0;}while (remaining > 0) { nr = read(localSkipBuffer, 0, (int) Math.min(SKIP_BUFFER_SIZE, remaining)); if (nr < 0) {break; } remaining -= nr;}return n - remaining; }
可以优化为:
public long skip(long n) throws IOException {if (n <= 0) { return 0;}int i=0;while ( read() != -1 && i < n) { i++;}return i;}
这样即节省了skipBuffer 2048个空间,代码也更简单;
继续看了一下子类的代码,都覆盖了这个方法。但优化后的方法总比优化前强!public int read(byte b[], int off, int len) throws IOException {if (b == null) { throw new NullPointerException();} else if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException();} else if (len == 0) { return 0;}int c = read();if (c == -1) { return -1;}b[off] = (byte)c;int i = 1;try { for (; i < len ; i++) {c = read();if (c == -1) { break;}if (b != null) { b[off + i] = (byte)c;} }} catch (IOException ee) {}return i; }
如果从硬盘读数据是一块一块读的,如果内存中读数据的话,比如数组的copy,肯定先申请一段空间,然后是一个一个读的和写。