FileChannel类的简单用法

清单一:

  1. importjava.io.*;
  2. importjava.nio.*;
  3. importjava.nio.channels.*;
  4. publicclassGetChannel
  5. {
  6. privatestaticfinalintBSIZE=1024;
  7. publicstaticvoidmain(String[]args)throwsIOException
  8. {
  9. FileChannelfc=newFileOutputStream("data.txt").getChannel();
  10. fc.write(ByteBuffer.wrap("sometxt".getBytes()));//write()Writesasequenceofbytesto
  11. //thischannelfromthegivenbuffer
  12. fc.close();
  13. fc=newRandomAccessFile("data.txt","rw").getChannel();
  14. fc.position(fc.size());//abstractFileChannelposition(longnewPosition)
  15. //Setsthischannel'sfileposition.
  16. fc.write(ByteBuffer.wrap("somemore".getBytes()));
  17. fc.close();
  18. fc=newFileInputStream("data.txt").getChannel();
  19. ByteBufferbf=ByteBuffer.allocate(BSIZE);//staticByteBufferallocate(intcapacity)
  20. //Allocatesanewbytebuffer.
  21. //一旦调用read()来告知FileChannel向ByteBuffer存储字节,就必须调用缓冲器上的filp(),
  22. //让它做好别人存储字节的准备(是的,他是有点拙劣,但请记住他是很拙劣的,但却适于获取大速度)
  23. //
  24. fc.read(bf);//Readsasequenceofbytesfromthischannelintothegivenbuffer
  25. bf.flip();
  26. while(bf.hasRemaining())
  27. System.out.print((char)bf.get());
  28. }
  29. }

清单二:

  1. //Copyingafileusingchannelsandbuffers;
  2. importjava.io.*;
  3. importjava.nio.*;
  4. importjava.nio.channels.*;
  5. publicclassChannelCopy
  6. {
  7. privatestaticfinalintBSIZE=1024;
  8. publicstaticvoidmain(String[]args)throwsIOException
  9. {
  10. if(args.length!=2)
  11. {
  12. System.out.println("argument:sourcefiledestfile");
  13. System.exit(1);
  14. }
  15. FileChannel
  16. in=newFileInputStream(args[0]).getChannel(),
  17. out=newFileOutputStream(args[1]).getChannel();
  18. ByteBufferbb=ByteBuffer.allocate(BSIZE);
  19. while(in.read(bb)!=-1)
  20. {
  21. bb.flip();
  22. out.write(bb);
  23. bb.clear();//prepareforreading;清空缓冲区;
  24. }
  25. }
  26. }

清单三

  1. importjava.io.*;
  2. importjava.nio.*;
  3. importjava.nio.channels.*;
  4. publicclassTransferTo
  5. {
  6. publicstaticvoidmain(String[]args)throwsIOException
  7. {
  8. if(args.length!=2)
  9. {
  10. System.out.println("argument:sourcefiledestfile");
  11. System.exit(1);
  12. }
  13. FileChannel
  14. in=newFileInputStream(args[0]).getChannel(),
  15. out=newFileOutputStream(args[1]).getChannel();
  16. //abstractlongtransferTo(longposition,longcount,WritableByteChanneltarget)
  17. //Transfersbytesfromthischannel'sfiletothegivenwritablebytechannel.
  18. in.transferTo(0,in.size(),out);
  19. //or
  20. //usingout
  21. //abstractlongtransferFrom(ReadableByteChannelsrc,longposition,longcount)
  22. //Transfersbytesintothischannel'sfilefromthegivenreadablebytechannel.
  23. //out.transferFrom(in,0,in.size());
  24. }
  25. }

你可能感兴趣的:(java)