NIO Channel을 통해서 4GB 이상 대용량 파일을 옮기기 위해서 만들어본 예제입니다.

자바 7버전에서 나온 try-closeable 문을 사용해보았으며(try-catch-finally에서 finally에서 객체를 닫아줄 필요없이 try 문의 괄호 안에 매개변수로 선언해서 사용하면

try 문이 끝나고 알아서 닫힘)


fcin.transferTo() 가 복사를 진행하는 메서드이며 원본파일이 대용량인 경우 파일을 한꺼번에 복사할 수 없음으로

일정량씩 계속 복사를 진행합니다.

Main 메서드 밑에 getMeasuredByte 함수가 일정량 복사가 되었을 때 그 크기를 cmd에 보여주기 위해서 만든 메서드입니다.






import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.channels.FileChannel; public class AutoFileCopy { private final static String SOURCE_FILE = "C:\\Users\\JuJin\\Desktop\\다운로드\\영화.avi"; private final static String TO_FILE = "F:\\영\\영화.avi"; public static void main(String[] args) { long fsize = 0; long prevTime = System.currentTimeMillis(); long elapsedTime = 0; long position = 0; try (FileInputStream fis = new FileInputStream(SOURCE_FILE + item); FileOutputStream fos = new FileOutputStream(TO_FILE + item); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel()) { fsize = fcin.size(); System.out.println("copy..."); while (position < fcin.size()) { long count = fcin.transferTo(position, fsize, fcout); if (count > 0) { position += count; fsize -= count; System.out.println(getMeasuredByte(position) + "/" + getMeasuredByte(fcin.size()) + " copyed."); } } } catch (Exception e2) { System.out.println("오류 발생"); e2.printStackTrace(); } System.out.println("Copy is done."); System.out.println("Name: " + item); System.out.println("Size: " + getMeasuredByte(position)); System.out.println("-------------------------------------------------------------------"); } } private static String getMeasuredByte(long byteSize) { final int KILOBYTE_UNIT = 1000; final int MEGABYTE_UNIT = 1000 * KILOBYTE_UNIT; final long GIGABYTE_UNIT = 1000 * MEGABYTE_UNIT; final long TERABYTE_UNIT = 1000 * GIGABYTE_UNIT; String measured = ""; if (byteSize < KILOBYTE_UNIT) measured = byteSize + "B"; else if (byteSize < MEGABYTE_UNIT) measured = String.format("%.2fKB", ((float) byteSize / KILOBYTE_UNIT)); else if (byteSize < GIGABYTE_UNIT) measured = String.format("%.2fMB", ((float) byteSize / MEGABYTE_UNIT)); else if (byteSize < TERABYTE_UNIT) measured = String.format("%.2fGB", ((float) byteSize / GIGABYTE_UNIT)); return measured; } }


'자바 > JAVA' 카테고리의 다른 글

자바를 이용한 srt 자막에서 대본만들기  (0) 2017.07.21

+ Recent posts