private byte[] loadClassFromFile(String filename) {
byte[] buffer = new byte[1024];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int len = 0;
try (InputStream inputStream = getClass().getClassLoader()
.getResourceAsStream(filename.replace('.', File.separatorChar) + ".class")) {
if (null == inputStream) {
return byteArrayOutputStream.toByteArray();
}
while ((len = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(Arrays.copyOf(buffer, len));
}
} catch (IOException e) {
e.printStackTrace();
}
return byteArrayOutputStream.toByteArray();
}
private byte[] loadClassFromFile(String fileName) {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(
fileName.replace('.', File.separatorChar) + ".class");
byte[] buffer;
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
int nextValue = 0;
try {
while ( (nextValue = inputStream.read()) != -1 ) {
byteStream.write(nextValue);
}
} catch (IOException e) {
e.printStackTrace();
}
buffer = byteStream.toByteArray();
return buffer;
}
结论:第一个会更快
buffer是一个大小为1024的字节数组,也就是1KB,所以
inputStream.read(buffer)一次可以从流中读取1KB的数据
,并将读取的数据放入到byteArrayOutputStream。而inputStream.read()一次只读取一个字节
,每次一读完就要放到byteArrayOutputStream,效率会比较低,而且每次write时,byteArrayOutputStream还有额外的判断动作,需要判断内部的字节数组是否足够存放,如果不够,需要将内部字节数组的大小变为原来的两倍
。源码如下