11 июл 2006 11:52 | |
Сообщения:7
|
Помогите плз. Как скопировать из одной папки в другую если в исходной есть вложенные папки и файлы?
|
11 июл 2006 15:51 | |
Сообщения:3874
|
private static void recurseIt(File fromDir, File toDir, boolean overwrite) throws IOException, FileNotFoundException { System.out.println("Copy directory content from [" + fromDir.getCanonicalPath() + "] to [" + toDir.getCanonicalPath() + "]"); if (fromDir.isDirectory()) { File[] files = fromDir.listFiles(); for (int i = 0; i < files.length; i++) { File destFile = new File(toDir.getCanonicalPath() + File.separator + files[i].getName()); System.out.println("Copying [" + files[i].getCanonicalPath() + "] to [" + destFile.getCanonicalPath() + "]"); // Source file is a file if (files[i].isFile()) { if (destFile.exists() && overwrite) destFile.delete(); if (!destFile.exists()) { if (!destFile.createNewFile()) throw new IllegalStateException("Destination file [" + destFile.getCanonicalPath() + "] could not be created!"); copyFile(files[i], destFile); } else { System.out.println("File [" + destFile.getCanonicalPath() + "," + destFile.length() + "B ] already exists!"); } } else { // Source file is a directory if (!destFile.exists()) { System.out.println("Creating destination directory [" + destFile.getCanonicalPath() + "]"); if (!destFile.mkdirs()) throw new IllegalStateException("Destination directory [" + destFile.getCanonicalPath() + "] could not be created!"); } recurseIt(files[i], destFile, overwrite); } } } } private static void copyFile(File from, File to) throws FileNotFoundException, IOException { BufferedInputStream in = new BufferedInputStream(new FileInputStream(from)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(to)); int read; byte[] buffer = new byte[1024]; try { while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } finally { out.flush(); in.close(); out.close(); } } public static void copyDir(File fromDir, File toDir, boolean overwrite) throws IOException, FileNotFoundException { // Perform some validation if (!fromDir.exists() || !fromDir.canRead()) throw new IllegalArgumentException("Directory [" + fromDir.getCanonicalPath() + "] does not exists or cannot be read!"); if (!toDir.exists()) if (!toDir.mkdirs()) throw new IllegalStateException("Destination directory [" + toDir.getCanonicalPath() + "] cound not be created!"); if (!toDir.isDirectory()) throw new IllegalStateException("Destination directory [" + toDir.getCanonicalPath() + "] is not valid!"); recurseIt(fromDir, toDir, overwrite); } public static void main(String[] args) { try { copyDir(new File("C:\\Temp"), new File("D:\\Temp"), false); } catch (Exception ex) { ex.printStackTrace(); } } |
Изменен:11 июл 2006 12:55 |
11 июл 2006 15:54 | |
Сообщения:7
|
Спасибо, большое. Я это протестью. Но уже думаю заранее. Это работает.
|