on
【Java-파일】파일복사
【Java-파일】파일복사
1. 설명
이 포스트에서 다루는 예제는 파일을 복사하는 코드입니다.
2. 소스코드
- 메서드
public boolean copy(String originPath, String destPath, boolean rename) throws IOException { File originFile = new File(originPath); if ( !originFile.exists() ) { return false; // 복사할 파일 } File destFile = new File(destPath); if ( destFile.exists() && !rename ) { return false; // 결과 파일이 이미 존재하며, 덮어쓰기 플래그가 false라면 } InputStream is = null; OutputStream os = null; try { is = new FileInputStream(originFile); os = new FileOutputStream(destFile); byte [] buff = new byte[1024]; int length; while ((length = is.read(buff)) > 0) { os.write(buff, 0, length); } return true; } finally { is.close(); is = null; os.close(); os = null; } }
- 메인
public class File_04_Copy { public static void main(String[] args) { try { for (String str : args ) { System.out.println("Param : "+str); } // Case 1 : 파일 복사 String oldPath1 = args[0]; String newPath1 = args[1]; // Case 2 : 파일 복사(덮어쓰기) String oldPath2 = args[2]; String newPath2 = args[3]; FileUtil fu = new FileUtil(); System.out.println("Case 1 : "+ fu.copy(oldPath1, newPath1, false)); System.out.println("Case 2 failure : "+ fu.copy(oldPath2, newPath2, false)); System.out.println("Case 2 success : "+ fu.copy(oldPath2, newPath2, true)); System.exit(0); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }
3. 실행결과【Windows(이클립스) / Linux】
4. 전체코드
https://github.com/leeyoungseung/template-java
from http://koiking.tistory.com/29 by ccl(A) rewrite - 2021-09-12 12:01:20