【问题标题】:Counting bytes consumed by char streams计算 char 流消耗的字节数
【发布时间】:2013-10-17 20:09:10
【问题描述】:

我在磁盘上有一个大文本文件 (csv),我将其分成几行。像这样的:

BufferedReader reader = new BufferedReader(new FileReader(file));
while ((line = reader .readLine()) != null) { 
   ...
}

我想要做的是计算每 1,000 行的文件开头的偏移量,所以如果将来我想读取第 10,001 行,我可以直接跳转到偏移量 X,然后开始迭代。

文件可以以任何方式编码,因此字节和字符之间没有强关系。

有没有人知道任何“计数读者”或替代方法?我很高兴自己实现了一个 Reader,但如果可以避免的话,我不想写一个非常复杂的类。

【问题讨论】:

    标签: java io nio


    【解决方案1】:

    当你需要随机访问时,BufferedReader 不适合。相反,您需要查看Channel 及其子类,如FileChannel 等。

    使用通道读取的简单示例:

        RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw");
        FileChannel inChannel = aFile.getChannel();
    
        ByteBuffer buf = ByteBuffer.allocate(48);
    
        int bytesRead = inChannel.read(buf);
        while (bytesRead != -1) {
    
          System.out.println("Read " + bytesRead);
          buf.flip();
    
          while(buf.hasRemaining()){
              System.out.print((char) buf.get());
          }
    
          buf.clear();
          bytesRead = inChannel.read(buf);
        }
        aFile.close();  
    

    来源:http://tutorials.jenkov.com/java-nio/channels.html

    至于您从上次中断的地方读取的问题,FileChannel 定义了一个方法read(ByteBuffer buf,int position),其中 position 是您想要读取的字节位置。

    【讨论】:

    • 谢谢 - 但我如何确定 1,000 字节偏移线的起始位置?
    • @Kong 如果您的行长度相等,那很好,否则您需要以一种告诉您每行占用多少字节的方式来构造文件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 2019-08-08
    • 2019-04-19
    相关资源
    最近更新 更多