Java复制目录/子目录/文件
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.List; /** * 文件拷贝 * @author lixiaolong */ public class FileTransfer { /** * 使用通道的方式进行整个目录/子目录/文件的拷贝 * @throws IOException */ public void useChannel() throws IOException { String driver = "F:\\AgileController"; String path = "/tomcat/webapps/OPMUI/customize"; File input = new File(driver + path); String bakpath = "\\syncbak"; File bakFile = new File(driver + bakpath); if(bakFile.exists()) { deleteFile(bakFile); } bakFile.mkdirs(); File output = new File(driver + bakpath + path); if(input.isDirectory()) { output.mkdirs(); List<File> allFileList = new ArrayList<File>(); getAllFiles(input, allFileList); for(File f : allFileList) { String outputPath = f.getCanonicalPath(); if(outputPath.startsWith(driver)) { outputPath = driver + bakpath + outputPath.substring(driver.length(), outputPath.length()); } output = new File(outputPath); if(f.isDirectory()) { output.mkdirs(); } else { fileCopy(f, output); } } } else { fileCopy(input, output); } } /** * 递归列出所有子目录/文件 * @param directory * @param allFileList */ private void getAllFiles(File directory, List<File> allFileList) { File flist[] = directory.listFiles(); if (flist == null || flist.length == 0) { return; } for (File f : flist) { if (f.isDirectory()) { //列出所有子文件夹 allFileList.add(f); getAllFiles(f, allFileList); } else { //列出所有文件 allFileList.add(f); } } } /** * 使用通道的方式对单个文件进行拷贝 * @param input * @param output * @throws IOException */ private void fileCopy(File input, File output) throws IOException { if(!input.exists()) { return; } if(!output.exists()) { output.createNewFile(); } FileInputStream fis = new FileInputStream(input); FileOutputStream fos = new FileOutputStream(output); FileChannel inputChannel = null; FileChannel outputChannel = null; try { inputChannel = fis.getChannel(); outputChannel = fos.getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); } finally { inputChannel.close(); outputChannel.close(); fis.close(); fos.close(); } } /** * 级联删除文件 * @param file */ private void deleteFile(File file) { if (file.isDirectory()) { File[] files = file.listFiles(); for (File f : files) { f.delete(); } } file.delete(); } public static void main(String[] args) { FileTransfer ft = new FileTransfer(); try { ft.useChannel(); } catch (IOException e) { System.out.println(e); } System.out.println("end"); } }