Java一次读取文本文件所有内容

本文介绍了一种高效的Java文本文件读取方法,通过一次性读取文件全部内容至内存并进行编码转换,避免了多次文件访问及逐行读取带来的性能损失。
Java一次读取文本文件所有内容
标签: javaencodingstringfilebytenull
6793人阅读 评论(0) 收藏 举报
本文章已收录于:
分类:
我们做文本处理的时候的最常用的就是读写文件了,尤其是读取文件,不论是什么文件,我都倾向于一次性将文本的原始内容直接读取到内存中再做处理,当然,这需要你有一台大内存的机器,内存不够者……可以一次读取少部分内容,分多次读取。
读取文件效率最快的方法就是一次全读进来,很多人用readline()之类的方法,可能需要反复访问文件,而且每次readline()都会调用编码转换,降低了速度,所以,在已知编码的情况下,按字节流方式先将文件都读入内存,再一次性编码转换是最快的方式,典型的代码如下:
  1. public String readToString(String fileName) {  
  2.         String encoding = "ISO-8859-1";  
  3.         File file = new File(fileName);  
  4.         Long filelength = file.length();  
  5.         byte[] filecontent = new byte[filelength.intValue()];  
  6.         try {  
  7.             FileInputStream in = new FileInputStream(file);  
  8.             in.read(filecontent);  
  9.             in.close();  
  10.         } catch (FileNotFoundException e) {  
  11.             e.printStackTrace();  
  12.         } catch (IOException e) {  
  13.             e.printStackTrace();  
  14.         }  
  15.         try {  
  16.             return new String(filecontent, encoding);  
  17.         } catch (UnsupportedEncodingException e) {  
  18.             System.err.println("The OS does not support " + encoding);  
  19.             e.printStackTrace();  
  20.             return null;  
  21.         }  
  22.     }  
public String readToString(String fileName) {
		String encoding = "ISO-8859-1";
		File file = new File(fileName);
		Long filelength = file.length();
		byte[] filecontent = new byte[filelength.intValue()];
		try {
			FileInputStream in = new FileInputStream(file);
			in.read(filecontent);
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			return new String(filecontent, encoding);
		} catch (UnsupportedEncodingException e) {
			System.err.println("The OS does not support " + encoding);
			e.printStackTrace();
			return null;
		}
	}

转自 http://hi.baidu.com/bluejade_zhou/blog/item/e09084da573bc2d4b7fd4831.html

 
 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值