2014.11.19超级复制

<h2><span style="font-size:18px;color:#ff0000;"><strong>1.</strong></span></h2><pre name="code" class="java"><span style="font-size:18px;">package com.hechao;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.channels.FileChannel;

public class SuperCopy {
	/**
	 * IO文件拷贝
	 * @param o	需拷贝对象
	 * @return	拷贝的新对象
	 * @throws Exception	拷贝异常
	 */
	@SuppressWarnings("unchecked")
	public static <T extends Serializable> T deepClone(T o) throws Exception {
		// 将对象序列化到内存中
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(out);
		oos.writeObject(o);
		// 从内存中反序列化对象
		ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
		ObjectInputStream ois = new ObjectInputStream(in);
		return (T) ois.readObject();
	}

	/**
	 * NIO拷贝文件
	 * @param in	需拷贝的目标文件
	 * @param out	拷贝后的新文件
	 * @throws Exception	拷贝异常
	 */
	public static void copyFile(File in, File out) throws Exception {
		//创建输出通道
		@SuppressWarnings("resource")
		FileChannel sourceChannel = new FileInputStream(in).getChannel();
		//创建输入通道
		@SuppressWarnings("resource")
		FileChannel destinationChannel = new FileOutputStream(out).getChannel();
		//将输入通道的数据传输到输出通道
		sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
		//关闭通道
		sourceChannel.close();
		destinationChannel.close();
		sourceChannel = null;
		destinationChannel = null;
	}
}
</span>

2.

<span style="font-size:18px;">package com.hechao;

import java.io.File;
/**
 * NIO文件拷贝测试
 * @author hechao
 *
 */
public class Test01 {
	public static void main(String[] args) {
		File in = new File("C:/Users/hechao/Desktop/JavaIO-9.wmv");
		File out = new File("D:/javasp.wmv");
		try {
			SuperCopy.copyFile(in, out);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
</span>




                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值