美文网首页
Java 快速按行读取文件

Java 快速按行读取文件

作者: 沧浪之水v | 来源:发表于2019-11-01 13:59 被阅读0次

起因: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<String> lines = FileUtils.readLines(f, "UTF-8");

            for (String line : lines) {
                System.out.println(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

相关文章

  • Java 快速按行读取文件

    起因:Java的IO总是很繁琐,而且需要你显式地处理IO抛出的异常,在一般的脚本化处理起来非常麻烦。每次仅仅是需要...

  • Python IO 流

    转载请注明出处 读文件 读取整个文件 分段读取 按行读取代码 按行读取 二进制读取 写文件 文本写出 追加文件 二...

  • Java读取文件方法汇总

    这篇文章主要为大家详细介绍了Java读取文件方法,按字节读取文件内容、按字符读取文件内容、随机读取文件内容等,具有...

  • Java读取文件方法汇总

    这篇文章主要为大家详细介绍了Java读取文件方法,按字节读取文件内容、按字符读取文件内容、随机读取文件内容等,具有...

  • Java中按行读取文件

    本文译自Java read a file line by line – How Many Ways? 转载请注明出...

  • go实现按行读取文件

    go实现按行读取文件(附案例) 按行读取文件并筛选打印数据func ReadLineFile(fileName s...

  • Python3 读取文件内容

    简单粗暴读取文件里面每一行 快速的读取文件里面每一行 遍历文件夹里所有文件,读取里面每一行

  • gradle文件操作

    读取文件,按行读取 写文件,如果文件不存在则创建,覆盖写

  • shell读取文件三种方法

    Shell按行读取文件的3种方法 Shell按行读取文件的方法有很多,常见的三种方法如下: 要读取的文件: 写法一...

  • 常用模块

    文件操作## 读取文件 可以使用with块缩短代码 分块读取 按行读取:如果要一次性读取所有行,只需调用readl...

网友评论

      本文标题:Java 快速按行读取文件

      本文链接:https://www.haomeiwen.com/subject/mgiiyctx.html