为什么java bytebuffer.getlong()/getint() - 方法不返回预期的int-number



以下类将读取从文本文件中的长效到缓冲区。该值被用来更改Filechannel的位置,在该位置将其读取到缓冲区中的另一个值。通过getint() - 方法,最后一个值被打印为int。

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class ReadChannelTest {
    public static void main(String[] args) {
        Path file2 = Paths.get("C:\Users\XXXXX\Desktop\datafile.txt");
        OpenOption rd = StandardOpenOption.READ;
        try( SeekableByteChannel in2 = FileChannel.open(file2, rd )){
            ByteBuffer buf =  ByteBuffer.allocate(64);
            in2.position(0);
            in2.read(buf);
            buf.rewind();

            long pos = buf.getLong();
            System.out.println("Read position: " + pos);
            in2.position(pos);
            buf.rewind();
            in2.read(buf);
            System.out.print("The int value: "+buf.getInt());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

控制台显示以下输出:

Read position: 3756037515073552384    
The int value: 874520608

datafile.txt看起来像这样:

4   89

我希望将4个被读取到字节案中,并用它将通道的位置更改为4。但是,最终, 807411744 ,而不是 8 。出去。这是为什么?为什么Pos-Value 3756037515073552384 而不是 4

非常感谢。

-mrfunkus

getLong()读取ByteBuffer的前8个字节并将其转换为 long

it 不会将文本分解为数字。请参阅:

https://docs.oracle.com/javase/7/docs/api/java/nio/nio/bytebuffer.html#getlong()

您可能想使用Scanner

请参阅:https://docs.oracle.com/javase/7/docs/api/java/java/util/scanner.html#nextint()

最新更新