package com.java; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class CopyFile { public static void main(String[] args) { File fromFile = new File("E:\\游戏\\英雄联盟"); File toFile = new File("F:\\游戏\\英雄联盟"); copyFile(fromFile, toFile); } public static void copyFile(File fromFile,File toFile) { //判断是否是文件夹 boolean isDir = fromFile.isDirectory(); if(isDir) {//是文件夹 toFile.mkdirs(); System.out.println("创建文件夹:"+toFile.getPath()); File[] listFiles = fromFile.listFiles(); for (File file : listFiles) {//遍历listFiles数组 copyFile(file,new File(toFile.getPath()+"/"+file.getName())); } }else { writeFile(getFileBytes(fromFile), toFile);//复制文件 System.out.println("复制文件:"+fromFile.getPath()+"\\"+fromFile.getName()+"------>"+toFile.getPath()+"\\"+toFile.getName()); } } /** * 读取文件字节数组 * @param file 要读取的文件 * @return 字节数组 */ public static byte[] getFileBytes(File file) { FileInputStream fileInputStream = null; byte[] fileBytes = null; try { fileInputStream = new FileInputStream(file); try { fileBytes = new byte[fileInputStream.available()]; fileInputStream.read(fileBytes); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); }finally { if(fileInputStream!=null) { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return fileBytes; } /** * 复制文件 * @param fileBytes 原文件的字节数组 * @param file 新文件 */ public static void writeFile(byte[] fileBytes,File file) { FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(file); try { fileOutputStream.write(fileBytes); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); }finally { if(fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
JAVA IO流实现递归复制文件
最新推荐文章于 2021-11-10 20:40:52 发布