起因:Java的IO总是很繁琐,而且需要你显式地处理IO抛出的异常,在一般的脚本化处理起来非常麻烦。每次仅仅是需要一个需求,那就是——快速按行读取文件,但是总是要查半天!
记录一下快速的按行读取文件的代码。
我们知道Python什么的很好用:open --> read... read... -> close就好了,而JAVA很烦。
传统的
private static void readFile2(File fin) throws IOException {
// Construct BufferedReader from FileReader
BufferedReader br = new BufferedReader(new FileReader(fin));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
try with resource
File file = new File("F:\\dogData\\VCF2Tree\\eGPS_result_ydl20190902\\sample.csv");
try (BufferedReader br = new BufferedReader(new FileReader(file));) {
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
java8
Charset charset = Charset.forName("US-ASCII");
try (BufferedReader reader = Files.newBufferedReader(file, charset)) {
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
第三方库
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class ReadTextFile {
public static void main(String[] args) throws IOException {
try {
File f = new File("src/com/mkyong/data.txt");
System.out.println("Reading files using Apache IO:");
List lines = FileUtils.readLines(f, "UTF-8");
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}