Вопрос

I've been getting some strange outputs from this code upon reading from a large file, the file was printed using a while loop to 99,999 digits however, upon reading the file and printing the contents it only outputs 99,988 lines. Also, is using a ByteBuffer the only option for reading back the file? I've seen some other code using a CharBuffer, but I'm not sure which one I should use, and in what cases I should use them. NOTE: filePath is a Path object pointing to a file on the disk.

    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();
            }
        }
Это было полезно?

Решение

Usually, flip() is called before buffer data is read. the rewind() method does bellowing works:

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

it does not set the 'limit' as flip() does:

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

So, take a tray using flip() instead of rewind() before reading.

Другие советы

For reading text BufferedReader is the best

    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);

is equivalent to

Charset.defaultCharset();

Well, it actually turns out that this combination works:

    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();
            }
        }
    }

As to why it works, i am not quite certain.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top