首页 文章

Java使用FileChannel从文件中读取

提问于
浏览
0

从大型文件读取时,我从这段代码中获得了一些奇怪的输出,文件使用while循环打印到99,999位,但是在读取文件并打印内容时它只输出99,988行 . 另外,使用ByteBuffer是读回文件的唯一选择吗?我已经看过一些使用CharBuffer的其他代码,但我不确定应该使用哪一个,以及在什么情况下我应该使用它们 . 注意:filePath是指向磁盘上文件的Path对象 .

private void byteChannelTrial() throws Exception {
        try (FileChannel channel = (FileChannel) Files.newByteChannel(filePath, READ)) {
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            String encoding = System.getProperty("file.encoding");
            while (channel.read(buffer) != -1) {
                buffer.rewind();
                System.out.print(Charset.forName(encoding).decode(buffer));
                buffer.clear();
            }
        }

3 回答

  • 2

    通常,在读取缓冲区数据之前调用flip() . rewind()方法确实如下工作:

    public final Buffer rewind() {
        position = 0;
        mark = -1;
        return this;
    }
    

    它没有像flip()那样设置'limit':

    public final Buffer flip() {
        limit = position;
        position = 0;
        mark = -1;
        return this;
    }
    

    因此,在阅读之前使用flip()而不是倒带()来托盘 .

  • 1

    对于阅读文本,BufferedReader是最好的

    try (BufferedReader rdr = Files.newBufferedReader(Paths.get("path"),
                Charset.defaultCharset())) {
            for (String line; (line = rdr.readLine()) != null;) {
                System.out.println(line);
            }
        }
    

    BTW

    String encoding = System.getProperty("file.encoding");
    Charset.forName(encoding);
    

    相当于

    Charset.defaultCharset();
    
  • 0

    嗯,事实证明这个组合有效:

    private void byteChannelTrial() throws Exception {
            try (FileChannel channel = (FileChannel) Files.newByteChannel(this.filePath, READ)) {
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                while (channel.read(buffer) != -1) {
                    buffer.flip();
                    System.out.print(Charset.defaultCharset().decode(buffer));
                    buffer.clear();
                }
            }
        }
    

    至于它为何起作用,我不太确定 .

相关问题