/**
* 通道对通道复制效率高
* @param f1
* 源文件
* @param f2
* 目的文件
* @return
* @throws Exception
*/
public static long forChannel(File f1, File f2) throws Exception {
long time = new Date().getTime();
int length = 2097152; //每次以2m速度传输
FileInputStream in = new FileInputStream(f1);
FileOutputStream out = new FileOutputStream(f2);
// 创建输入,输出通道
FileChannel inC = in.getChannel();
FileChannel outC = out.getChannel();
ByteBuffer b = null;
while (true) {
if (inC.position() == inC.size()) {
inC.close();
outC.close();
return new Date().getTime() - time;
}
if ((inC.size() - inC.position()) < length) {
length = (int) (inC.size() - inC.position());
} else
length = 2097152;
b = ByteBuffer.allocateDirect(length);
inC.read(b);
b.flip();
outC.write(b);
outC.force(false);
}
}
/*
* 复制整个文件夹内容
*
* @param oldPath String 原文件路径 如:c:/old (注意参数的路径格式)
*
* @param newPath String 复制后路径 如:f:/new
*
* @return boolean
*/
private static void copyFolder(String oldPath, String newPath) {
try {
(new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
File a = new File(oldPath);
String[] file = a.list();
File temp = null;
// 复制文件夹
if (file != null) {
for (int i = 0; i < file.length; i++) {
if (oldPath.endsWith(File.separator)) {
temp = new File(oldPath + file[i]);
} else {
temp = new File(oldPath + File.separator + file[i]);
}
// 处理文件
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath
+ "/" + (temp.getName()).toString());
byte[] b = new byte[1024 * 5];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if (temp.isDirectory()) {// 如果是子文件夹 ,使用递归
copyFolder(oldPath + "/" + file[i], newPath + "/"
+ file[i]);
}
}
}
else{
String orgFileName = oldPath.substring(oldPath.lastIndexOf("/"),oldPath.length());
System.out.println(orgFileName );
// 复制单个文件
forChannel(new File(oldPath),new File(newPath+ "/"+orgFileName));
}
} catch (Exception e) {
System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();
}
}
发散:通过这样复制方式去实现文件上传,应该没有问题吧?!
前提是上传到应用服务器上而不是web服务器上