티스토리 뷰

java.io.FileInputStream/ FileOutputStream - 파일복사

파일 복사 할 대상의 파일은 FileInputStream 으로 선언하고, 새로운 파일의 대상은 FileOutputStream 를 이용한다.  

FileOutputStream 생성

// File 의 위치를 인수로
FileOutputStream ex1 = new FileOutputStream(String name);
// 기존의 파일이 있는 경우 이어서 쓸지 여부 
FileOutputStream ex2 = new FileOutputStream(String name, blooen append);
FileInputStream ex3 = new FileInputStream(new File("path"));
FileInputStream ex3 = new FileInputStream(new File("path"), blooen append);

예제 1

package com.athlete.file; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class FileCopy { public static void main(String[] args) { FileInputStream input = null; FileOutputStream output = null; try{ // 복사할 대상 파일을 지정해준다. File file = new File("c:\\example\\File\\umejintan_new.txt"); // FileInputStream 는 File object를 생성자 인수로 받을 수 있다. input = new FileInputStream(file); // 복사된 파일의 위치를 지정해준다. output = new FileOutputStream(new File("c:\\example\\File\\umejintan_copy.txt")); int readBuffer = 0; byte [] buffer = new byte[512]; while((readBuffer = input.read(buffer)) != -1) { output.write(buffer, 0, readBuffer); } System.out.println("파일이 복사되었습니다."); } catch (IOException e) { System.out.println(e); } finally { try{ // 생성된 InputStream Object를 닫아준다. input.close(); // 생성된 OutputStream Object를 닫아준다. output.close(); } catch(IOException io) {} } } }

결과

FileInputStream 의 read() 통해서 읽어 들인 바아트 배열의 Data를 저장한 후 FileOutputStream 의 wtite() 메소드를 이용하여 파일 출력을 한다.



댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함