java 拷贝文件夹

来源:互联网 发布:淘宝收购kfc 编辑:程序博客网 时间:2024/05/20 10:22
package util;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;/** * 文件操作助手类 * @author Administrator * */public class FileUtils {/** * 拷贝文件或文件夹 */public static void copy(File from, File to){if(from.isDirectory()){//拷贝文件夹if(!to.exists())to.mkdirs();File[] children = from.listFiles();for(File f : children){String path = to.getAbsolutePath() + "/" + f.getName();copy(f, new File(path));}}else{//文件try {InputStream is = new FileInputStream(from);OutputStream os = new FileOutputStream(to);byte[] bts = new byte[2048];int len = is.read(bts);while(len > 0){os.write(bts, 0, len);len = is.read(bts);}is.close();os.close();System.out.println("已拷贝文件:" + to.getAbsolutePath());} catch (Exception e) {throw new RuntimeException("将文件" + from.getAbsolutePath() + "拷到" + to.getAbsolutePath() + "失败!", e);}}}}


 

原创粉丝点击