필기노트

JAVA FileChannel을 이용한 파일전송 본문

JAVA

JAVA FileChannel을 이용한 파일전송

우퐁코기 2023. 1. 4. 07:03
반응형

파일 전송을 할 때 FileChannel이 가장 효율적이다.

import java.nio.channels.FileChannel;

public class FileMove {
    public static void main(String[] args) throws IOException {
        File myFile = new File("C:"+File.separator+"MyJava"+File.separator+"my.bin");
        File reFile = new File("C:"+File.separator+"YourJava"+File.separator+"my.bin");
        if(myFile.exists()==false)
        {
            System.out.println("원본 파일이 준비되어 있지 않습니다.");
            return;
        }

        FileInputStream fileInputStream = new FileInputStream(myFile);
        FileOutputStream fileOutputStream = new FileOutputStream(reFile);

        FileChannel fcin = fileInputStream.getChannel();
        FileChannel fcout = fileOutputStream.getChannel();

        long size = fcin.size();
        fcin.transferTo(0, size, fcout);

        if(reFile.exists()==true)
            System.out.println("파일 전송에 성공하였습니다.");
        else
            System.out.println("파일 전송에 실패하였습니다.");
            
        fcin.close();
        fcout.close();
    }
}
반응형

'JAVA' 카테고리의 다른 글

자바 File 클래스, renameTo  (0) 2023.01.20
JAVA 소켓 통신(Socket, Server, Client)  (1) 2023.01.19
map 반복 및 람다, 스트림  (0) 2022.12.24
JAVA Apache POI로 Word 치환하기  (0) 2022.12.24
자바 FileInputStream, FileOutputStream  (0) 2022.07.20
Comments