JAVA中几种读取文件字符串的效率哪个比较高

如题所述

方式一

/**
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
* 当然也是可以读字符串的。
*/
/* 貌似是说网络环境中比较复杂,每次传过来的字符是定长的,用这种方式?*/
public String readString1()
{
try
{
//FileInputStream 用于读取诸如图像数据之类的原始字节流。要读取字符流,请考虑使用 FileReader。
FileInputStream inStream=this.openFileInput(FILE_NAME);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int length=-1;
while( (length = inStream.read(buffer) != -1)
{
bos.write(buffer,0,length);
// .write方法 SDK 的解释是 Writes count bytes from the byte array buffer starting at offset index to this stream.
// 当流关闭以后内容依然存在
}
bos.close();
inStream.close();
return bos.toString();
// 为什么不一次性把buffer得大小取出来呢?为什么还要写入到bos中呢? return new(buffer,"UTF-8") 不更好么?
// return new String(bos.toByteArray(),"UTF-8");
}
}

方式二

// 有人说了 FileReader 读字符串更好,那么就用FileReader吧
// 每次读一个是不是效率有点低了?
private static String readString2()
{
StringBuffer str=new StringBuffer("");
File file=new File(FILE_IN);
try {
FileReader fr=new FileReader(file);
int ch = 0;
while((ch = fr.read())!=-1 )
{
System.out.print((char)ch+" ");
}
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("File reader出错");
}
return str.toString();
}
温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答