Here you can find the source of copy(final File source, final File target)
Parameter | Description |
---|---|
source | the source file or directory. |
target | the target file or directory. |
Parameter | Description |
---|---|
IOException | when IO error occur. |
public static void copy(final File source, final File target) throws IOException
//package com.java2s; //License from project: Apache License import java.io.*; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; public class Main { /**/* w w w .jav a 2 s . c om*/ * Copy. * * @param source the source file or directory. * @param target the target file or directory. * @throws IOException when IO error occur. */ public static void copy(final File source, final File target) throws IOException { if (source == null) throw new NullPointerException("source directory is null."); if (target == null) throw new NullPointerException("target directory is null."); if (source.isFile()) { File parentFolder = target.getParentFile(); if (parentFolder != null) { parentFolder.mkdirs(); } Files.copy(source.toPath(), target.toPath(), StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); } else if (source.isDirectory()) { Files.walkFileTree(source.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { Files.createDirectories(target.toPath().resolve(source.toPath().relativize(dir))); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { Files.copy(file, target.toPath().resolve(source.toPath().relativize(file)), StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); return FileVisitResult.CONTINUE; } }); } } }