---
title: "NIO的使用（FileInputStream/FileOutputStream）"
author: "lylegend13"
date: "2011-10-17T13:34:34Z"
tags: []
categories: ["编程语言"]
slug: "nio-fileinputstream-fileoutputstream"
draft: false
lastmod: "2011-10-17T13:34:59Z"
id: 1198353
url: "https://lltobe.iteye.com/blog/1198353"
---

```
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();
				}
			}
		}
	}
}
```