[Java] 자바로 파일 복사하는 3가지 방법

    자바로 파일을 복사하는 3가지 방식을 설명해보도록 하겠습니다. 이것 이외에도 다양한 라이브러리를 사용해서 복사하는 방법들이 있지만, 아래의 방식만 알아도 큰 문제는 없을거라 판단해서 3가지를 선정해보았습니다.

     

    [Java] 자바로 파일 복사하는 3가지 방법


    1. FileInputStream/FileOutputStream 방식

    우선 가장 고전적인 방식으로 InputStream, OutputStream 을 사용하여 byte를 복사하는 방식입니다.

    public static void main(String args[]) {
        String orgFilePath = "D:/test_copy/original.jpg";
        String outFilePath = "D:/test_copy/copy.jpg";
        System.out.println("status -> " + fileCopy(orgFilePath, outFilePath));
    }
    
    public static boolean fileCopy(String inFilePath, String outFilePath) {
        try {
            FileInputStream infile = new FileInputStream(inFilePath);
            FileOutputStream outfile = new FileOutputStream(outFilePath);
    
            byte[] b = new byte[1024];
            int len;
            while((len = infile.read(b, 0, 1024)) > 0){
                outfile.write(b, 0, len);
            }
            infile.close();
            outfile.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    
        return true;
    }

    위 방식은 JDK(1.7 이전 버전에 많이 사용)가 많이 바뀐 현재는 사용 추세가 점차 줄어들고 있습니다.

     

    2. Files.Copy 방식

    java.nio 패키지를 사용하여 쉽게 copy를 하는 방식으로 보다 진보적인 방식입니다. 기본적으로 nio 패키지가 io 패키지를 개선하기 위해서 나왔고, 코드량도 대폭 줄일 수 있습니다.

    import java.nio.file.Files;
    import java.nio.file.StandardCopyOption;
    
    public static void main(String args[]) {
        String orgFilePath = "D:/test_copy/original.jpg";
        String outFilePath = "D:/test_copy/copy.jpg";
    
        System.out.println("status -> " + nioCopy(orgFilePath, outFilePath));
    }
    
    public static boolean nioCopy(String inFilePath, String outFilePath) {
        File orgFile = new File(inFilePath);
        File outFile = new File(outFilePath);
    
        try {
            Files.copy(orgFile.toPath(), outFile.toPath(),
                            StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

     

    3. FileUtils 방식

    FileUtils 방식은 Apache의 Commons-io 라이브러리를 사용하여 구현하는 방식이며, 별도의 라이브러리를 추가해야 합니다.

     

     

    pom.xml

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.11.0</version>
    </dependency>

    Code

    import org.apache.commons.io.FileUtils;
    
    public static void main(String args[]) {
        String orgFilePath = "D:/test_copy/original.jpg";
        String outFilePath = "D:/test_copy/copy.jpg";
    
        System.out.println("status -> " + commonCopy(orgFilePath, outFilePath));
    }
    
    public static boolean commonCopy(String inFilePath, String outFilePath) {
        File orgFile = new File(inFilePath);
        File outFile = new File(outFilePath);
    
        try {
            FileUtils.copyFile(orgFile, outFile);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

     

    전체 코드

    import org.apache.commons.io.FileUtils;
    
    import java.io.*;
    import java.nio.file.Files;
    import java.nio.file.StandardCopyOption;
    
    public class Main {
    
        public static void main(String args[]) {
            String orgFilePath = "D:/test_copy/original.jpg";
            String outFilePath = "D:/test_copy/copy.jpg";
    
            System.out.println("status -> " + fileCopy(orgFilePath, outFilePath));
            System.out.println("status -> " + nioCopy(orgFilePath, outFilePath));
            System.out.println("status -> " + commonCopy(orgFilePath, outFilePath));
        }
    
        public static boolean fileCopy(String inFilePath, String outFilePath) {
            try {
                FileInputStream infile = new FileInputStream(inFilePath);
                FileOutputStream outfile = new FileOutputStream(outFilePath);
    
                byte[] b = new byte[1024];
                int len;
                while((len = infile.read(b, 0, 1024)) > 0){
                    outfile.write(b, 0, len);
                }
                infile.close();
                outfile.close();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
    
            return true;
        }
    
        public static boolean nioCopy(String inFilePath, String outFilePath) {
            File orgFile = new File(inFilePath);
            File outFile = new File(outFilePath);
    
            try {
                Files.copy(orgFile.toPath(), outFile.toPath(),
                                StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
            return true;
        }
    
        public static boolean commonCopy(String inFilePath, String outFilePath) {
            File orgFile = new File(inFilePath);
            File outFile = new File(outFilePath);
    
            try {
                FileUtils.copyFile(orgFile, outFile);
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
            return true;
        }
    }
    

     

    댓글

    Designed by JB FACTORY