DirectBuffer.java 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package cn.hhj.nio.buffer;
  2. import java.io.*;
  3. import java.nio.*;
  4. import java.nio.channels.*;
  5. /**
  6. * 直接缓冲区
  7. * Zero Copy 减少了一个拷贝的过程
  8. */
  9. public class DirectBuffer {
  10. static public void main( String args[] ) throws Exception {
  11. //在Java里面存的只是缓冲区的引用地址
  12. //管理效率
  13. //首先我们从磁盘上读取刚才我们写出的文件内容
  14. String infile = "E://test.txt";
  15. FileInputStream fin = new FileInputStream( infile );
  16. FileChannel fcin = fin.getChannel();
  17. //把刚刚读取的内容写入到一个新的文件中
  18. String outfile = String.format("E://testcopy.txt");
  19. FileOutputStream fout = new FileOutputStream(outfile);
  20. FileChannel fcout = fout.getChannel();
  21. // 使用allocateDirect,而不是allocate
  22. ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
  23. while (true) {
  24. buffer.clear();
  25. int r = fcin.read(buffer);
  26. if (r==-1) {
  27. break;
  28. }
  29. buffer.flip();
  30. fcout.write(buffer);
  31. }
  32. }
  33. }