这是一个非常简单的例子,它会告诉你如何阅读您数据顺序:
public void readFile(String absoluteFilePath){
ByteBuffer buf = ByteBuffer.allocate(2+4+8) // creating a buffer that is suited for data you are reading
Path path = Paths.get(absoluteFilePath);
try(FileChannel fileChannel = (FileChannel)Files.newByteChannel(path,Enum.setOf(READ))){
while(true){
int bytesRead = fileChannel.read(buf);
if(bytesRead==-1){
break;
}
buf.flip(); //get the buffer ready for reading.
char c = buf.asCharBuffer().readChar(); // create a view buffer and read char
buf.position(buf.position() + 2); //now, lets go to the int
int i = buf.asIntBuffer().readInt(); //read the int
buf.position(buf.position()+ 4); //now, lets go for the double.
double d = buf.asDoubleBuffer().readDouble();
System.out.println("Character: " + c + " Integer: " + i + " Double: " + d);
buf.clear();
}
}catch(IOException e){
e.printStackTrace();
}// AutoClosable so no need to explicitly close
}
现在,假设你总是写数据(字符, int,double)插入到文件中,并且没有机会将数据乱序或不完整为(char,int)/(char,double),您可以通过指定文件中的位置来随机读取数据,以字节测量,从那里到数据获取:
channel.read(byteBuffer,position);
在你的情况下,数据的大小始终是14个字节作为2 + 4 + 8,以便所有的读位置将是14的倍数。
First block at: 0 * 14 = 0
Second block at: 1 * 14 = 14
Third block at: 2 * 14 = 28
等..
类似的阅读,您也可以编写使用
channel.write(byteBuffer,position)
同样,位置将是14
倍数这适用于FileChannel
情况下这是一个超类的ReadableByteChannel
其是用于读出的专用信道,WritableByteChannel
其是用于写入的专用信道和SeekableByteChannel
这可以做读写,但有点复杂。
当使用通道和ByteBuffer时,注意如何阅读。没有任何东西阻止我读取14个字节作为一组7个字符。虽然这看起来很可怕,但这会让您完全灵活地读取和写入数据。
什么错误?你能告诉我们你如何阅读文件吗? – david 2013-04-27 18:28:39
你开什么错误? – 2013-04-27 18:28:43
问题是,你在你的二进制文件中随机写入'char','double'和'int',所以在读它时你不知道如何读取它,也就是说我必须先读一个'char',一个'double'还是'int'? – 2013-04-27 18:28:56