Programing

Java에서 파일 이동 / 복사 작업

lottogame 2020. 11. 1. 17:13
반응형

Java에서 파일 이동 / 복사 작업


파일 / 폴더 이동 / 복사와 같은 일반적인 파일 작업을 처리하는 표준 Java 라이브러리가 있습니까?


작업으로이를 수행하는 방법은 다음과 java.nio같습니다.

public static void copyFile(File sourceFile, File destFile) throws IOException {
    if(!destFile.exists()) {
        destFile.createNewFile();
    }

    FileChannel source = null;
    FileChannel destination = null;
    try {
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();

        // previous code: destination.transferFrom(source, 0, source.size());
        // to avoid infinite loops, should be:
        long count = 0;
        long size = source.size();              
        while((count += destination.transferFrom(source, count, size-count))<size);
    }
    finally {
        if(source != null) {
            source.close();
        }
        if(destination != null) {
            destination.close();
        }
    }
}

아직은 아니지만 New NIO (JSR 203) 는 이러한 일반적인 작업을 지원합니다.

그 동안 명심해야 할 몇 가지 사항이 있습니다.

File.renameTo는 일반적으로 동일한 파일 시스템 볼륨에서만 작동합니다. 나는 이것을 "mv"명령과 동등하다고 생각한다. 가능한 경우 사용하되 일반적인 복사 및 이동 지원을 위해서는 대체가 필요합니다.

이름 변경이 작동하지 않으면 실제로 파일을 복사해야합니다 ( "이동"작업 인 경우 File.delete로 원본 삭제 ). 이를 가장 효율적으로 수행하려면 FileChannel.transferTo 또는 FileChannel.transferFrom 메소드를 사용하십시오 . 구현은 플랫폼에 따라 다르지만 일반적으로 한 파일에서 다른 파일로 복사 할 때 구현은 커널과 사용자 공간 사이에서 데이터를주고받는 것을 방지하여 효율성을 크게 향상시킵니다.


확인 : http://commons.apache.org/io/

사본이 있으며 언급했듯이 JDK에는 이미 이동이 있습니다.

자신의 복사 방법을 구현하지 마십시오. 저기 떠 다니는 게 너무 많아 ...


이전 답변은 구식 인 것 같습니다.

Java의 File.renameTo () 는 아마도 API 7을위한 가장 쉬운 솔루션이며 잘 작동하는 것 같습니다. 예외를 던지지는 않지만 true / false를 반환합니다.

이전 버전에서는 문제가있는 것 같습니다 ( NIO 와 동일 ).

이전 버전을 사용해야하는 경우 여기를 확인 하십시오 .

다음은 API7의 예입니다.

File f1= new File("C:\\Users\\.....\\foo");
File f2= new File("C:\\Users\\......\\foo.old");
System.err.println("Result of move:"+f1.renameTo(f2));

또는 :

System.err.println("Move:" +f1.toURI() +"--->>>>"+f2.toURI());
Path b1=Files.move(f1.toPath(),  f2.toPath(), StandardCopyOption.ATOMIC_MOVE ,StandardCopyOption.REPLACE_EXISTING ););
System.err.println("Move: RETURNS:"+b1);

Google의 Guava 라이브러리에는 다음이 있습니다.

http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/io/Files.html


org.apache.commons.io.FileUtils (일반 파일 조작 유틸리티)를 사용해보십시오 . 시설은 다음과 같은 방법으로 제공됩니다.

(1) FileUtils.moveDirectory (File srcDir, File destDir) => 디렉토리를 이동합니다.

(2) FileUtils.moveDirectoryToDirectory(File src, File destDir, boolean createDestDir) => Moves a directory to another directory.

(3) FileUtils.moveFile(File srcFile, File destFile) => Moves a file.

(4) FileUtils.moveFileToDirectory(File srcFile, File destDir, boolean createDestDir) => Moves a file to a directory.

(5) FileUtils.moveToDirectory(File src, File destDir, boolean createDestDir) => Moves a file or directory to the destination directory.

It's simple, easy and fast.


Interesting observation: Tried to copy the same file via various java classes and printed time in nano seconds.

Duration using FileOutputStream byte stream: 4 965 078

Duration using BufferedOutputStream: 1 237 206

Duration using (character text Reader: 2 858 875

Duration using BufferedReader(Buffered character text stream: 1 998 005

Duration using (Files NIO copy): 18 351 115

when using Files Nio copy option it took almost 18 times longer!!! Nio is the slowest option to copy files and BufferedOutputStream looks like the fastest. I used the same simple text file for each class.

참고URL : https://stackoverflow.com/questions/300559/move-copy-file-operations-in-java

반응형