代码:
package nio.buffer; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; /** * @author songyan * @date 2020年4月21日 * @desc: */ public class Test1 { public static void main(String[] args) { FileChannel fc = null; try { FileInputStream fis = new FileInputStream("F://test.txt"); fc = fis.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(10); printInfo("init",buffer); fc.read(buffer); printInfo("read",buffer); buffer.flip(); printInfo("flip",buffer); while(buffer.remaining()>0){ byte b = buffer.get(); printInfo("get",buffer); } buffer.clear(); printInfo("clear",buffer); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { fc.close(); } catch (IOException e) { e.printStackTrace(); } } } private static void printInfo(String status,ByteBuffer buffer) { System.out.println(status+":"); System.out.println("capacity:"+buffer.capacity()+";position:"+buffer.position()+";limit:"+buffer.limit()); } }