最近在做一个语料的清洗程序,需要读取大量的txt文件的内容,然后对内容进行一系列的清洗,这时有两种处理方案,一是用readline()一行一行读取然后拼接起来,二是一次性读取,我倾向于一次性将文本的原始内容直接读取到内存中再做处理,因为涉及的文件量很大,几十、几百G的几十万个文件,这样提升一点速度,整体就能提升很大的速度。当然,这需要你有一台大内存的机器,内存不够者……可以一次读取少部分内容,分多次读取。
读取文件效率最快的方法就是一次全读进来,很多人用readline()之类的方法,可能需要反复访问文件,而且每次readline()都会调用编码转换,再把字符串拼接起来,降低了速度,所以,在已知编码的情况下,按字节流方式先将文件都读入内存,再一次性编码转换是最快的方式,两种情况的代码如下:
readline()方法:
public String getContent(File file){
StringBuffer sb = new StringBuffer();
try {
String encoding="UTF-8";
if(file.isFile() && file.exists()){ //判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file),encoding);//考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while((lineTxt = bufferedReader.readLine()) != null){
sb.append(lineTxt);
}
read.close();
}else{
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
return sb.toString();
}
字节流一次读取:
public String getContent(File file) throws Exception {
String encoding="UTF-8";
byte[] filecontent = {};
if(file.isFile() && file.exists()){ //判断文件是否存在
Long filelength = file.length();
filecontent = new byte[filelength.intValue()];
FileInputStream in = new FileInputStream(file);
in.read(filecontent);
in.close();
}else{
System.out.println("找不到指定的文件");
}
return new String(filecontent, encoding);
}