利用缓存读取文件提高性能

前段时间写了个程序需要对文件进行读取操作,一开始使用最普通的写法
		FileReader in = new FileReader("E:/a.html");
BufferedReader br = new BufferedReader(in);
String string="",str="";
while((string=br.readLine())!=null){
str+=string;
}
System.out.println(str);

但是当正式开始运行的时候发现用是可以用但效率过于低下(因为每次运行都要读取几十甚至上百个的文件,所以效率问题很明显),所以就上网搜索了一些提高IO流的资料,发现大多数都是说使用缓存,于是就上网搜了一段代码
     * 使用缓存区读写文件  
* @param from
* @param to
* @throws IOException
*/
public static void readWriteWithBuffer(String from, String to)
throws IOException {
InputStream inBuffer = null;
OutputStream outBuffer = null;
try {
inBuffer = new BufferedInputStream(new FileInputStream(from));
outBuffer = new BufferedOutputStream(new FileOutputStream(to));
while (true) {
int data = inBuffer.read();
if (data == -1) {
break;
}
outBuffer.write(data);
}
} finally {
if (inBuffer != null) {
inBuffer.close();
}
if (outBuffer != null) {
outBuffer.close();
}
}
}

}

但发现无法直接将字符串存入内存进行其他操作,于是又搜索了一些资料,发现原来只要用byte转一下即可,最终代码如下

File file = new File( "E:/a.html");
InputStream input = null;
input = new FileInputStream(file);
String str = "";
byte[] b = new byte[(int)file.length()];
input.read(b);
input.close();
str=new String(b);
System.out.println(str);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值