java - 计算 char 流消耗的字节数

标签 java io nio

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

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

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

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

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

最佳答案

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

使用 channel 读取的简单示例:

    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,intposition),其中position是以字节为单位的位置,其中yu想要阅读。

关于java - 计算 char 流消耗的字节数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19436278/

相关文章:

java - JdbcBatchItemWriter 是否不支持 List<Map> 输入项?

c 使用 fgets、strtok 读取文件导致段错误

c# - 如何使用C#将WAV文件拆分为两个或更多部分

java - RandomAccessFile 与 FileChannel.open(path);

java - 如何正确使用 ClassLoader.getResources()?

java - 为什么没有在 Hashmap 中调用 equals 方法?

java - 什么相当于 ruby​​ 的 rack 或 python 的 Java wsgi?

io - 有没有办法将 []byte slice 转换为 io.Reader?

java - 在 jetty 使用 NIO 与 BIO 的优势?

java - NIO连接断开时未获取readyKey