我一次读取一个510字节的文件。字节位于字节缓冲区中,我正在使用fileChannel读取它们。
一旦我改变了位置,它就会再次检查while循环中的情况,然后跳出while循环。总字节数约为8000字节。如何在不引起此错误的情况下,将其回滚到fileChannel中的特定位置?
这是我的代码:
File f = new File("./data.txt");
FileChannel fChannel = f.getChannel();
ByteBuffer bBuffer = ByteBuffer.allocate(510);
while(fChannel.read(bBuffer) > 0){
//omit code
if(//case){
fChannel.position(3060);
}}
发布于 2014-11-16 06:08:18
如果您的ByteBuffer已满,read()将返回零,您的循环将终止。您需要flip()您的ByteBuffer,从其中提取数据,然后compact()为更多的数据腾出空间。
发布于 2016-06-16 18:51:35
我还为以字节形式读取文件做了大量工作。一开始,我意识到有这样一种灵活的机制是很好的,这样你就可以设置文件的位置和字节大小,最后得到下面的代码。
public static byte[] bytes;
public static ByteBuffer buffer;
public static byte[] getBytes(int position)
{
try
{
bytes=new byte[10];
buffer.position(position);
buffer.get(bytes);
}
catch (BufferUnderflowException bue)
{
int capacity=buffer.capacity();
System.out.println(capacity);
int size=capacity-position;
bytes=new byte[size];
buffer.get(bytes);
}
return bytes;
}在这里,您还可以通过传递参数大小和位置来使字节数组的大小变得灵活。下面的异常将在这里处理。希望它能帮助你;
https://stackoverflow.com/questions/26953964
复制相似问题