Java笔记··By/蜜汁炒酸奶

Java逐行读取文件

BufferedReader方式的关键代码

通过桥接器InputStreamReader将FileInputStream文件字节输入流转为字符流

由BufferedReader设置缓冲区并包装InputStreamReader的read()操作,调用readLine()方法逐行读取。

// 创建path文件的文件字节输入流
FileInputStream fileInputStream = new FileInputStream(path);
// 创建从字节流到字符流的桥接器
InputStreamReader isr = new InputStreamReader(fileInputStream, "UTF-8");
// 创建一个使用指定大小输入缓冲区的缓冲字符输入流,用于包装InputStreamReader的read()操作
BufferedReader reader = new BufferedReader(isr, 5*1024*1024);
// 通过reader.readLine()逐行读取
while ((tem = reader.readLine()) != null) {
    // 处理读取的数据
}
// 关闭相关流
reader.close();
isr.close();
fileInputStream.close();
1
2
3
4
5
6
7
8
9
10
11
12
13
14

FileChannel方式的关键代码

基于文件通道的nio方式,判断是否含有换行符,从而实现逐行读取数据。

可以考虑通过fileChannel.position(startIndex);将该方式扩展为多线程操作,此时暂时不再展开。

// 分配一个新的字节缓冲区。
ByteBuffer rbuf = ByteBuffer.allocate(1024);
// 创建path文件的文件字节输入流
FileInputStream fileInputStream = new FileInputStream(path);
// 获取通道
FileChannel fileChannel = fileInputStream.getChannel();
// 获取此通道文件的当前大小,作为文件结束位置
long endIndex = fileChannel.size();
// 当前处理字节所在位置
long endLineIndex = startIndex;
// 用于判断数据是否读取完
boolean isEnd = false;
// 换行符,目前需手动指定
int CF = "\n".getBytes()[0];
// 循环读取通道中的数据并放入rbuf中
while (fileChannel.read(rbuf) != -1) {
    // 创建与rbuf容量一样大的数组
    byte[] rbyte = new byte[rbuf.position()];
    // 读/写指针position指到缓冲区头部,并设置了最大读取长度
    rbuf.flip();
    // 将rbuf中的数据传输到rbyte中
    rbuf.get(rbyte);
    // 每行的起始位下标,相当于当前所读取到的byte数组
    int startNum = 0;
    // 循环读取rbyte,判断是否有换行符
    for (int i = 0; i<rbyte.length; i++) {
        endLineIndex++;
        // 当存在换行符时
        if (rbyte[i]== CF) {
            // 创建临时数组用于保存整行数据
            byte[] line = new byte[temp.length + i - startNum +1];
            // 将上次读取剩下的部分存入line
            System.arraycopy(temp, 0, line, 0, temp.length);
            // 将读取到的当前rbyte中的数据追加到line
            System.arraycopy(rbyte,startNum, line, temp.length, i- startNum +1);
            // 更新下一行起始位置
            startNum = i + 1;
            // 初始化temp数组
            temp = new byte[0];
            // 处理数据,此时line即为要处理的一整行数据
            String lineStr = new String(line,ENCODE);
            // 略过具体处理步骤
            // ......

        }
    }
    // 说明rbyte最后还剩不完整的一行
    if (startNum < rbyte.length) {
        byte[] temp2 = new byte[temp.length+rbyte.length - startNum];
        System.arraycopy(temp,0 ,temp2, 0, temp.length);
        System.arraycopy(rbyte, startNum, temp2, temp.length, rbyte.length - startNum);
        temp = temp2;
    }
    rbuf.clear();
}
// 兼容最后一行没有换行的情况
if (temp.length>0) {
    // 处理数据,此时line即为要处理的一整行数据
    String lineStr = new String(temp,ENCODE);
    // 略过具体处理步骤
    // ......
}
// 关闭通道
fileChannel.close();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

参考资料

java读取大文件并添加入库,按行读取

使用 java nio 实现按行读写文件

预览
Loading comments...
0 条评论

暂无数据

example
预览