Here you can find the source of copyFilesRecursive(File src, File dest)
Parameter | Description |
---|---|
src | the source file to copy. Can be a file or a directory. |
dest | the destination to copy to. Can be a file or directory. |
Parameter | Description |
---|
public static List<File> copyFilesRecursive(File src, File dest) throws IOException
//package com.java2s; /*/*from w ww. j a v a 2 s.c o m*/ * Copyright 2004 - 2012 Cardiff University. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.*; import java.util.ArrayList; import java.util.List; public class Main { /** * Copies files and directories recursively. The destination does not * have to exist yet. * * @param src the source file to copy. Can be a file or a directory. * @param dest the destination to copy to. Can be a file or directory. * @return a List of the newly created Files * @throws java.io.FileNotFoundException if src does not exist * @throws java.io.IOException if src is a directory and dest exists * and is not a directory, or an IO error occurs. */ public static List<File> copyFilesRecursive(File src, File dest) throws IOException { ArrayList<File> list = new ArrayList<File>(); if (!src.exists()) { throw new FileNotFoundException("Input file does not exist."); } if (src.isDirectory()) { if (!dest.exists()) { dest.mkdirs(); } else if (!dest.isDirectory()) { throw new IOException("cannot write a directory to a file."); } list.add(dest); File[] srcFiles = src.listFiles(); for (int i = 0; i < srcFiles.length; i++) { list.addAll(copyFilesRecursive(srcFiles[i], new File(dest, srcFiles[i].getName()))); } } else { if (dest.exists() && dest.isDirectory()) { dest = new File(dest, src.getName()); } BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); byte[] bytes = new byte[8192]; int c; while ((c = in.read(bytes)) != -1) { out.write(bytes, 0, c); } out.flush(); out.close(); in.close(); list.add(dest); } return list; } }