java中怎么将一个文件内容写入到另一个文件,这里使用nio来实现

java中怎么将一个文件内容写入到另一个文件,这里使用nio来实现

通道和缓冲器:通道是装满东西的房间,缓冲区就是一个卡车,到了目的地,在从缓冲区取下来
通道是目的地或者源头,缓冲器就是中间的
字节缓冲区类,就是唯一的直接和通道接通的缓冲区类
ByteBuffer是一个比较基础的类

方式一:出了两个通道,一个是目的地通道(channel2),一个是源头的通道(channel1),中间还需要一个大卡车(ByteBuffer)

package aboutIO;

import java.io.FileInputStream;

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

public class FileIO {
	public static void main(String[] args) {
		try {
			FileInputStream file1 = new FileInputStream("C://Users//ASUS//Desktop//a.txt");
			FileChannel channel = file1.getChannel();
			FileOutputStream file2 = new FileOutputStream("C://Users//ASUS//Desktop//b.txt");
			FileChannel channel2 = file2.getChannel();
			// 下边开始声明一个字节缓冲器
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			while (channel.read(buffer) != -1) {//将物品从库存读入到缓冲器(大卡车)
				buffer.flip();
				channel2.write(buffer);//将缓冲器(大卡车)的物品,写出到目的地。
				buffer.clear();

			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

//经过上边操作,就将我桌面文档中的a.txt中内容,复制到了我们的桌面的b.txt

java中怎么将一个文件内容写入到另一个文件,这里使用nio来实现

方式二:直接有通向两个地方的一个方法,卡车都省了。直接从一个地方丢到另一个地方:

package aboutIO;

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 FileIO2 {
	public static void main(String[] args) {
		try {
			FileInputStream file1 = new FileInputStream("C://Users//ASUS//Desktop//a.txt");
			FileChannel channel = file1.getChannel();
			FileOutputStream file2 = new FileOutputStream("C://Users//ASUS//Desktop//b.txt");
			FileChannel channel2 = file2.getChannel();
			// //下边开始声明一个字节缓冲器
			// ByteBuffer buffer=ByteBuffer.allocate(1024);
			// while(channel.read(buffer)!=-1){
			// buffer.flip();
			// channel2.write(buffer);
			// buffer.clear();
			// 使用下边一句来代替上边注释部分的作用
			channel.transferTo(0, channel.size(), channel2);//也可以使用transferFrom方法,参数需要修改即可

		} catch (

		IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}