Java NIO 拷贝文件(使用compact)

Java NIO 拷贝文件

实现方式一:

 

		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream("c:/ntldr");
			fos = new FileOutputStream("c:/ntldr.bak");
			FileChannel fic = fis.getChannel();
			FileChannel foc = fos.getChannel();
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			int bytesRead = 0;
			while (bytesRead >= 0 || buffer.hasRemaining()) {//---------(1)
				if (bytesRead != -1)
					bytesRead = fic.read(buffer);//-------------(2)
				buffer.flip();
				foc.write(buffer);
				buffer.compact();    //---------------(3)
			}

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

 说明:

2。 byteReads==-1表示输入源数据已经结束,但是buffer中仍旧还有数据。

3。在输入速度超过输出速度时,仍旧保留未输出的数据。

 

 

实现方式二:

public static void main(String[] args) {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream("c:/ntldr");
			fos = new FileOutputStream("c:/ntldr.bak");
			FileChannel fic = fis.getChannel();
			FileChannel foc = fos.getChannel();
			ByteBuffer buffer = ByteBuffer.allocate(1024);
			while(fic.read(buffer)!=-1){
				buffer.flip();
				while(buffer.hasRemaining()){ //----------------------(1)
					foc.write(buffer);
				}
				buffer.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();
				}
			}
		}

	}

 1.使用了双重循环。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值