Java 拷贝文件到指定目录下文件中

注:在使用之前请保证sFile,和 tFile存在可通过一下方法创建文件

    File tF = new File(sFile);
        if (!tF.exists()) {//判断存在
            tF.mkdirs();//不存在则重新创建多存目录
}

/* sFile:原文件地址,tFile目标文件地址 */

public void fileChannelCopy(String sFile, String tFile) {
FileInputStream fi = null;
FileOutputStream fo = null;
FileChannel in = null;
FileChannel out = null;
File s = new File(sFile);
File t = new File(tFile);
if (s.exists() && s.isFile()) {
try {
fi = new FileInputStream(s);
fo = new FileOutputStream(t);
in = fi.getChannel();// 得到对应的文件通道
out = fo.getChannel();// 得到对应的文件通道
in.transferTo(0, in.size(), out);// 连接两个通道,并且从in通道读取,然后写入out通道
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fi.close();
in.close();
fo.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}


小编自己也尝试实现了一下!下面是测试代码:

package com.my.demo;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 *实现文件copy
 * @author wyj
 *
 */
public class fileChannelCopy {
/*
* 目录F:\view.sql 拷贝到 F:\test\view.sql
* */

public static void main(String[] args) {
fileChannelCopy fcc = new fileChannelCopy();
File resfile = new File("F:\\view.sql");
if(resfile.exists()) {
if(resfile.isFile()) {

}else {
System.out.println("不是一个文件");
}
}else {
System.out.println("F:\\view.sql不存在");
return ;
}

File tfile = new File("F:\\test\\view.sql");
File filePath = tfile.getParentFile();
if(!filePath.exists()) {
filePath.mkdirs();
}
try {
tfile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fcc.copyFile(resfile,tfile);

}
private void copyFile(File resfile,File tfile) {
FileInputStream fis=null;
FileOutputStream fos=null;
FileChannel in=null;
FileChannel out = null;
try {
fis = new FileInputStream(resfile);
fos = new FileOutputStream(tfile);
in = fis.getChannel();// 得到对应的文件通道
out= fos.getChannel();// 得到对应的文件通道
long start = System.currentTimeMillis();   
in.transferTo(0, in.size(), out);// 连接两个通道,并且从in通道读取,然后写入out通道
long end = System.currentTimeMillis();        
      System.out.println("运行时间:"+(start-end)+"毫秒");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fis.close();
in.close();
fos.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

猜你喜欢

转载自blog.csdn.net/wyj823508/article/details/80183668