네로개발일기

개발자 네로의 개발 일기, 자바를 좋아합니다 !

반응형

Java 파일 복사하는 방법

1. FileInputStream, FileOutputStream

2. Files.copy()

3. FileChannel

4. Apache Commons IO

 

1. FileInputStream, FileoutputStream / BufferedInputStream, BufferedOutputStream

FileInputStream으로 파일을 읽고, FileOutputStream으로 새로운 파일을 쓴다.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream
import java.io.IOExeption;

public class CopyFile {

    public static void main(String[] args) {
        File file = new File ("/tmp/text.txt");
        File newFile = new File ("/tmp/new_text.txt");
        
        BufferedInputStream input = null;
        BufferedOuputStream output = null;
        try {
            input = new BufferedInputStream(new FileInputStream(file));
            output = new BufferedOutputStream(new FileOutputStream(newFile));
            
            byte[] readBuffer = new byte[1024];
            while(input.read(readBuffer, 0, readBuffer.length) != -1). {
                output.write(readBuffer);
            }
        } catch (Exception e) {
            // log
        } finally {
            input.close();
            output.close();
        }
    }
}

 

2. Files.copy()

java.nio.file.Files 클래스는 파일을 복사할 수 있는 copy() 메서드를 제공한다.

public static Path copy(Path source, Path target, CopyOption... options)

 파라미터 

- source: source file path

- target: target file path

- options

1. REPLACE_EXISTING: target 파일이 존재하면 덮어쓴다.

2. COPY_ATTRIBUTES: 파일 속성을 복사한다.

3. NOFOLLOW_LINKS: 파일이 symbolic link이면 링크 대상이 아닌, symbolic link 자체가 복사된다.

 

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class CopyFile {

    public static void main(String[] args) {
        File source = new File("/tmp/text.txt");
        File target = new File("/tmp/new_text.txt");
        
        Files.copy(source.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }
}

 

3. FileChannel

FileChannel 클래스는 파일의 읽기, 쓰기, 매핑 등을 위한 채널을 제공한다.

transferForm(), transferTo() 메서드를 사용하여 내용을 복사할 수 있다.

public abstract long transferForm(ReadableByteChannel src, long position, long count);

src 파일 채널로부터 position 위치부터 count 사이즈만큼 데이터를 복사한다.

public abstract long transferTo(long position, long count, WritableByteChannel target);

target 파일 채널로 position 위치부터 count 사이즈만큼 데이터를 복사한다.

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;

public class CopyFile {

    public static void main(String[] args) throw IOException {
        RandomAccessFile file = new RandomAccessFile("/tmp/text.txt", "r");
        RandomAccessFile newFile = new RandomAccessFile("/tmp/new_text.txt", "rw");
        
        FileChannel source = file.getChannel();
        FileChannel target = newFile.getChannel();
        
        source.transferTo(0, source.size(), target); 
        // 또는 
        // target.transferFrom(source, 0, source.size());
    }
}

 

4. Apache Commons IO

Apache Commons IO 라이브러리를 사용한다. (FileUtils 클래스의 copyFile() 메서드를 사용한다.)

public static void copyFile(File srcFile, File destFile);

 

Apache Commons IO를 사용하기 위해서 아래 dependency를 추가한다.

<dependency>
    <groupId>commons-io</groupId> 
    <artifactId>commons-io</artifactId>
    <version>2.9.0</version>
</dependency>
import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class CopyFile {

    public static void main(String[] args) throws IOException {
    
        File file = new File("/tmp/text.txt");
        File newFile = new File("/tmp/new_text.txt");
        
        FileUtils.copyFile(file, newFile);
    }
}

=> 비슷하게 Spring frameworkdp FileCopyUtils 클래스가 존재한다.

// FileCopyUtils.copy()
public static int copy(File in, File out);
public static int copy(Reader in, Writer out);
// ...

 

 

참고

https://hianna.tistory.com/604

 

[Java] 파일 복사하기

Java에서 파일을 다루는 방법을 알아보고 있습니다. [Java] 텍스트 파일 읽기 ( FileReader, BufferedReader, Scanner, Files ) [Java] 파일 생성하는 3가지 방법 (File, FileOutputStream, Files) [Java] 파일,..

hianna.tistory.com

 

728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !