java处理混合数据_Java I/O – 如何通过ByteBuffer从文件中读取混合数据

  • Post author:
  • Post category:java


import java.io.File;

import java.io.FileInputStream;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

public class Main {

public static void main(String[] args) throws Exception {

File aFile = new File(“main.java”);

FileInputStream inFile = new FileInputStream(aFile);

FileChannel inChannel = inFile.getChannel();

ByteBuffer lengthBuf = ByteBuffer.allocate(8);

while (true) {

if (inChannel.read(lengthBuf) == -1) {

break;

}

lengthBuf.flip();

int strLength = (int) lengthBuf.getDouble();

ByteBuffer buf = ByteBuffer.allocate(2 * strLength + 8);

if (inChannel.read(buf) == -1) {

break;

}

buf.flip();

byte[] strChars = new byte[2 * strLength];

buf.get(strChars);

System.out.println(strLength);

System.out.println(ByteBuffer.wrap(strChars).asCharBuffer());

System.out.println(buf.getLong());

lengthBuf.clear();

}

inFile.close();

}

}



版权声明:本文为weixin_33345728原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。