清单一:
- importjava.io.*;
- importjava.nio.*;
- importjava.nio.channels.*;
- publicclassGetChannel
- {
- privatestaticfinalintBSIZE=1024;
- publicstaticvoidmain(String[]args)throwsIOException
- {
- FileChannelfc=newFileOutputStream("data.txt").getChannel();
- fc.write(ByteBuffer.wrap("sometxt".getBytes()));//write()Writesasequenceofbytesto
- //thischannelfromthegivenbuffer
- fc.close();
- fc=newRandomAccessFile("data.txt","rw").getChannel();
- fc.position(fc.size());//abstractFileChannelposition(longnewPosition)
- //Setsthischannel'sfileposition.
- fc.write(ByteBuffer.wrap("somemore".getBytes()));
- fc.close();
- fc=newFileInputStream("data.txt").getChannel();
- ByteBufferbf=ByteBuffer.allocate(BSIZE);//staticByteBufferallocate(intcapacity)
- //Allocatesanewbytebuffer.
- //一旦调用read()来告知FileChannel向ByteBuffer存储字节,就必须调用缓冲器上的filp(),
- //让它做好别人存储字节的准备(是的,他是有点拙劣,但请记住他是很拙劣的,但却适于获取大速度)
- //
- fc.read(bf);//Readsasequenceofbytesfromthischannelintothegivenbuffer
- bf.flip();
- while(bf.hasRemaining())
- System.out.print((char)bf.get());
- }
- }
清单二:
- //Copyingafileusingchannelsandbuffers;
- importjava.io.*;
- importjava.nio.*;
- importjava.nio.channels.*;
- publicclassChannelCopy
- {
- privatestaticfinalintBSIZE=1024;
- publicstaticvoidmain(String[]args)throwsIOException
- {
- if(args.length!=2)
- {
- System.out.println("argument:sourcefiledestfile");
- System.exit(1);
- }
- FileChannel
- in=newFileInputStream(args[0]).getChannel(),
- out=newFileOutputStream(args[1]).getChannel();
- ByteBufferbb=ByteBuffer.allocate(BSIZE);
- while(in.read(bb)!=-1)
- {
- bb.flip();
- out.write(bb);
- bb.clear();//prepareforreading;清空缓冲区;
- }
- }
- }
清单三
- importjava.io.*;
- importjava.nio.*;
- importjava.nio.channels.*;
- publicclassTransferTo
- {
- publicstaticvoidmain(String[]args)throwsIOException
- {
- if(args.length!=2)
- {
- System.out.println("argument:sourcefiledestfile");
- System.exit(1);
- }
- FileChannel
- in=newFileInputStream(args[0]).getChannel(),
- out=newFileOutputStream(args[1]).getChannel();
- //abstractlongtransferTo(longposition,longcount,WritableByteChanneltarget)
- //Transfersbytesfromthischannel'sfiletothegivenwritablebytechannel.
- in.transferTo(0,in.size(),out);
- //or
- //usingout
- //abstractlongtransferFrom(ReadableByteChannelsrc,longposition,longcount)
- //Transfersbytesintothischannel'sfilefromthegivenreadablebytechannel.
- //out.transferFrom(in,0,in.size());
- }
- }