<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>