FileInputDemo.java 738 B

123456789101112131415161718192021222324252627282930
  1. package cn.hhj.nio.channel;
  2. import java.io.*;
  3. import java.nio.*;
  4. import java.nio.channels.*;
  5. public class FileInputDemo {
  6. static public void main( String args[] ) throws Exception {
  7. FileInputStream fin = new FileInputStream("E://test.txt");
  8. // 获取通道
  9. FileChannel fc = fin.getChannel();
  10. // 创建缓冲区
  11. ByteBuffer buffer = ByteBuffer.allocate(1024);
  12. // 读取数据到缓冲区
  13. fc.read(buffer);
  14. buffer.flip();
  15. while (buffer.remaining() > 0) {
  16. byte b = buffer.get();
  17. System.out.print(((char)b));
  18. }
  19. fin.close();
  20. }
  21. }