其实很简单,今天看了一个使用字符和字节不同读取和存取的例子:
private static void testOne(String filename) throws IOException {
FileInputStream fio=new FileInputStream(filename);
byte [] byt=new byte[8094];
int t;
StringBuffer sb=new StringBuffer();
while ((t=fio.read(byt))!=-1) {
sb.append(byt);
}
fio.close();
}
private static void testTwo(String filename) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
StringBuffer sb=new StringBuffer();
String str;
str=br.readLine();
while ((str=br.readLine())!=null) {
sb.append(str);
}
br.close();
}
方法testTwo的效率底就不用说了,但是在我使用一个大文件测试的时候,居然会出现OutofMemErr,如果说前面的读取的时候方式不同,但是存储有什么不同呢,看了下源码,StringBuffer在使用append方法时候,会使用内部缓冲区,如果溢出,则会申请新的缓冲数组,但是它和第一个方法那里不一样呢,在调用上,为什么它会报错溢出,第一个不会?
下午仔细跟踪了一下,发现原来是由于StringBuffer中对于字符和字节两种方式存储大小是不同的。至于为什么会不同,还有待进一步学习.