旧的I/O类库中有三个类被赋予了产生FileChannel的能力

旧的I/O类库中有三个类被修改了,用以产生FileChannel。来看看他们的例子:

package com.wjy.nio;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class GetChannel {
	private static final int BSIZE=1024;
	public static void main(String args[]){
		try {
			FileChannel fcChannel=new FileOutputStream(new File("./file/out.txt")).getChannel();
			fcChannel.write(ByteBuffer.wrap("Some text ".getBytes()));
			fcChannel.close();
			
			fcChannel=new RandomAccessFile(new File("./file/out.txt"), "rw").getChannel();
			fcChannel.position(fcChannel.size());  //移动到文件末尾,以添加内容
			fcChannel.write(ByteBuffer.wrap("randomaccessfile".getBytes()));
			fcChannel.close();
			
			fcChannel=new FileInputStream(new File("./file/out.txt")).getChannel();
			ByteBuffer buff=ByteBuffer.allocate(BSIZE);
			fcChannel.read(buff);
			buff.flip();	//这句很重要,没有这句出不来结果。一旦调用read()来向ByteBuffer存储字节,就必须调用缓冲器上的flip(),让它做好让别人读取字节的准备。
			while(buff.hasRemaining()){
				System.out.print((char)buff.get());
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 

/*OutPut
Some text randomaccessfile
*///

 号外:一旦调用read()来向ByteBuffer存储字节,就必须调用缓冲器上的flip(),让它做好让别人读取字节的准备。

 

请注意:如果打算使用缓冲器执行进一步的read()操作,我们也应该必须调用clead()为下次read()做好准备。所以,正常的过程应该是:

 

         while(in.read(buffer)!=-1)

              {

                  buffer.flip();    //准备好写

                  out.write(buffer);

                  buffer.clear();   //准备好读

              }

 

 

你可能感兴趣的:(FileChannel)