【发布时间】:2009-07-09 15:33:06
【问题描述】:
我有以下 FilterInputStream 的子类,只覆盖了一个方法。然而,这门课的表现太差了。它的运行速度是其超类的 1/10。我什至从 javasrc 的 InputStream 中获取了相同的源代码,并在我的子类中使用了它。同样的表现受到打击。覆盖类有什么问题吗?
public class NewLineStream extends FilterInputStream {
public NewLineStream(InputStream in) {
super(in);
}
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;
}
}
【问题讨论】:
-
是的,你一个一个地读取(),如果没有底层缓冲,它会很慢。
-
java.io.InputStream就是这样实现的,为什么那么快?
-
它是一个基类,每个实现都会覆盖它的方法。默认只是一个占位符。
-
你能展示一下你如何使用你的类的代码吗?
标签: java file-io performance