欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用FileChannel通道读写文件

程序员文章站 2022-04-24 15:01:11
...

使用FileChannel通道读写文件

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

public class ChannelTest {
public static void main(String[] args) {
	// TODO Auto-generated method stub
	ChannelTest ct = new ChannelTest();
	ct.writeFile();
	ct.readFile();
}
//写入文本文件
public void writeFile() {
	//1 创建输出流
	FileOutputStream fos = null;
	//2 获取通道
	FileChannel fc = null;
	try {
		//初始化输出流
		fos = new FileOutputStream("e:\\ex\\out.txt");
		//获取通道。通道是通过流获得的(注意!!!)
		fc = fos.getChannel();
		//3 创建缓冲区
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		//4 向缓冲区写入数据,把字符转成字节并写入缓冲区
		buffer.put("Whatever is worth doing is worth doing well.".getBytes());
		//改状态
		buffer.flip();
		//5 通过通道写入目标文件
		//FileChannel类中的.write()方法:将字节序列从给定的缓冲区写入此通道。
		fc.write(buffer);
		//6 关闭资源(在下面的finally中判断关闭)
		
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally{
		try {
			if(fc!=null) {
				fc.close();
			}
			if(fos!=null) {
				fos.close();
			}
		}catch(IOException ex){
			
		}
	}
}
public void readFile() {
	//创建流
	FileInputStream fis = null;
	FileChannel fc = null;
	
	try {
		fis = new FileInputStream("e:\\ex\\out.txt");
		fc = fis.getChannel();
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		int length = fc.read(buffer);
		buffer.flip();
		byte[] ary = new byte[length];
		//把缓冲区的内容获取后存入ary数组中
		buffer.get(ary);
		//clear并未清除内容,而是把position置0(注意!!!)
		buffer.clear();
		System.out.println(new String(ary));
		
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		try {
			if(fc!=null) {
				fc.close();
			}
			if(fis!=null) {
				fis.close();
			}
		}catch(IOException e) {
			e.printStackTrace();
		}
	  }
	}
 }