IT TIP

전체 디렉토리 내용을 다른 디렉토리로 복사 하시겠습니까?

itqueen 2020. 11. 29. 12:46
반응형

전체 디렉토리 내용을 다른 디렉토리로 복사 하시겠습니까?


이 질문에 이미 답변이 있습니다.

전체 디렉토리 내용을 Java 또는 Groovy의 다른 디렉토리로 복사하는 방법?


FileUtils.copyDirectory()

파일 날짜를 유지하면서 전체 디렉토리를 새 위치에 복사합니다. 이 메서드는 지정된 디렉터리와 모든 하위 디렉터리 및 파일을 지정된 대상으로 복사합니다. 대상은 디렉토리의 새 위치와 이름입니다.

대상 디렉토리가 없으면 생성됩니다. 대상 디렉터리가 존재하는 경우이 메서드는 원본을 우선 순위로하여 원본을 대상과 병합합니다.

이를위한 예제 코드는 다음과 같습니다.

String source = "C:/your/source";
File srcDir = new File(source);

String destination = "C:/your/destination";
File destDir = new File(destination);

try {
    FileUtils.copyDirectory(srcDir, destDir);
} catch (IOException e) {
    e.printStackTrace();
}

다음은 JDK7 사용 예입니다.

public class CopyFileVisitor extends SimpleFileVisitor<Path> {
    private final Path targetPath;
    private Path sourcePath = null;
    public CopyFileVisitor(Path targetPath) {
        this.targetPath = targetPath;
    }

    @Override
    public FileVisitResult preVisitDirectory(final Path dir,
    final BasicFileAttributes attrs) throws IOException {
        if (sourcePath == null) {
            sourcePath = dir;
        } else {
        Files.createDirectories(targetPath.resolve(sourcePath
                    .relativize(dir)));
        }
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(final Path file,
    final BasicFileAttributes attrs) throws IOException {
    Files.copy(file,
        targetPath.resolve(sourcePath.relativize(file)));
    return FileVisitResult.CONTINUE;
    }
}

방문자를 사용하려면 다음을 수행하십시오.

Files.walkFileTree(sourcePath, new CopyFileVisitor(targetPath));

차라리 모든 것을 인라인하고 싶다면 (자주 사용하면 너무 효율적이지 않지만 신속하게 사용하는 데 좋습니다)

    final Path targetPath = // target
    final Path sourcePath = // source
    Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(final Path dir,
                final BasicFileAttributes attrs) throws IOException {
            Files.createDirectories(targetPath.resolve(sourcePath
                    .relativize(dir)));
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(final Path file,
                final BasicFileAttributes attrs) throws IOException {
            Files.copy(file,
                    targetPath.resolve(sourcePath.relativize(file)));
            return FileVisitResult.CONTINUE;
        }
    });

Groovy를 사용하면 Ant활용 하여 다음을 수행 할 수 있습니다 .

new AntBuilder().copy( todir:'/path/to/destination/folder' ) {
  fileset( dir:'/path/to/src/folder' )
}

AntBuilder는 배포 및 자동 가져 오기 목록의 일부이므로 모든 그루비 코드에 직접 사용할 수 있습니다.


public static void copyFolder(File source, File destination)
{
    if (source.isDirectory())
    {
        if (!destination.exists())
        {
            destination.mkdirs();
        }

        String files[] = source.list();

        for (String file : files)
        {
            File srcFile = new File(source, file);
            File destFile = new File(destination, file);

            copyFolder(srcFile, destFile);
        }
    }
    else
    {
        InputStream in = null;
        OutputStream out = null;

        try
        {
            in = new FileInputStream(source);
            out = new FileOutputStream(destination);

            byte[] buffer = new byte[1024];

            int length;
            while ((length = in.read(buffer)) > 0)
            {
                out.write(buffer, 0, length);
            }
        }
        catch (Exception e)
        {
            try
            {
                in.close();
            }
            catch (IOException e1)
            {
                e1.printStackTrace();
            }

            try
            {
                out.close();
            }
            catch (IOException e1)
            {
                e1.printStackTrace();
            }
        }
    }
}


이것은 그루비 코드입니다. 테스트되었습니다.

private static void copyLargeDir(File dirFrom, File dirTo){
    // creation the target dir
    if (!dirTo.exists()){
        dirTo.mkdir();
    }
    // copying the daughter files
    dirFrom.eachFile(FILES){File source ->
        File target = new File(dirTo,source.getName());
        target.bytes = source.bytes;
    }
    // copying the daughter dirs - recursion
    dirFrom.eachFile(DIRECTORIES){File source ->
        File target = new File(dirTo,source.getName());
        copyLargeDir(source, target)
    }
}

어느 FileUtils.copyDirectory () 이나 아르키메데스의 응답 복사 디렉토리 속성 (파일 소유자, 권한, 수정 시간 등).

https://stackoverflow.com/a/18691793/14731 provides a complete JDK7 solution that does precisely that.


With coming in of Java NIO, below is a possible solution too

With Java 9:

private static void copyDir(String src, String dest, boolean overwrite) {
    try {
        Files.walk(Paths.get(src)).forEach(a -> {
            Path b = Paths.get(dest, a.toString().substring(src.length()));
            try {
                if (!a.toString().equals(src))
                    Files.copy(a, b, overwrite ? new CopyOption[]{StandardCopyOption.REPLACE_EXISTING} : new CopyOption[]{});
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    } catch (IOException e) {
        //permission issue
        e.printStackTrace();
    }
}

With Java 7:

import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.function.Consumer;
import java.util.stream.Stream;

public class Test {

    public static void main(String[] args) {
        Path sourceParentFolder = Paths.get("/sourceParent");
        Path destinationParentFolder = Paths.get("/destination/");

        try {
            Stream<Path> allFilesPathStream = Files.walk(sourceParentFolder);
            Consumer<? super Path> action = new Consumer<Path>(){

                @Override
                public void accept(Path t) {
                    try {
                        String destinationPath = t.toString().replaceAll(sourceParentFolder.toString(), destinationParentFolder.toString());
                        Files.copy(t, Paths.get(destinationPath));
                    } 
                    catch(FileAlreadyExistsException e){
                        //TODO do acc to business needs
                    }
                    catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }

            };
            allFilesPathStream.forEach(action );

        } catch(FileAlreadyExistsException e) {
            //file already exists and unable to copy
        } catch (IOException e) {
            //permission issue
            e.printStackTrace();
        }

    }

}

With regard to Java, there is no such method in the standard API. In Java 7, the java.nio.file.Files class will provide a copy convenience method.

References

  1. The Java Tutorials

  2. Copying files from one directory to another in Java


If you're open to using a 3rd party library, check out javaxt-core. The javaxt.io.Directory class can be used to copy directories like this:

javaxt.io.Directory input = new javaxt.io.Directory("/source");
javaxt.io.Directory output = new javaxt.io.Directory("/destination");
input.copyTo(output, true); //true to overwrite any existing files

You can also provide a file filter to specify which files you want to copy. There are more examples here:

http://javaxt.com/javaxt-core/io/Directory/Directory_Copy

참고URL : https://stackoverflow.com/questions/6214703/copy-entire-directory-contents-to-another-directory

반응형