import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ReadBinaryFile {
public static void main(String[] args) {
File aFile = new File("c:\\mm.txt");
FileInputStream inFile = null;
try{
inFile = new FileInputStream(aFile);
}catch(FileNotFoundException e){
e.printStackTrace();
}
//返回通道的初始 position 将等于到目前为止从文件中读取的字节数。
FileChannel inChannel = inFile.getChannel();//用于读取、写入、映射和操作文件的通道。
final int PRIMECOUNT = 6;//prime:初期,基本的。
ByteBuffer buf = ByteBuffer.allocate(8*PRIMECOUNT);//定义一个字节缓冲区分配空间为:
long[] primes = new long[PRIMECOUNT];//定义一个long数组
//inChannel.read 将字节序列从此通道读入给定的缓冲区。到达结尾返回-1
try{
while(inChannel.read(buf) != -1){
//flip()反转此缓冲区。首先将限制设置为当前位置,然后将位置设置为 0。如果已定义了标记,则丢弃该标记。
(((ByteBuffer)buf.flip())).asLongBuffer().get(primes);
for(long prime:primes){
System.out.printf("%10d",prime);
}
buf.clear();
}
inFile.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
读二进制文件11. 8. 10. Reading a Binary File
最新推荐文章于 2022-02-20 23:41:21 发布