ITeye博客

NIO的使用(FileInputStream/FileOutputStream)

lylegend13 · 2011-10-17 13:34 · Java · NIO · 编程语言 · Markdown

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 test4 {
	static public void main(String args[]) {
		FileInputStream fis = null;
		FileOutputStream fos = null;

		ByteBuffer bb = ByteBuffer.allocate(1024);
		try {
			fis = new FileInputStream("C:\\source.txt");
			fos = new FileOutputStream("C:\\copy.txt");

			FileChannel fci = fis.getChannel();
			FileChannel fco = fos.getChannel();

			while (-1 != fci.read(bb)) {
				bb.flip();
				fco.write(bb);
				bb.clear();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != fis) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != fos) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。