프로그래밍

[자바 기초] day14 : 파일입출력 예제(사진 복사하기) 본문

자바/자바 기초

[자바 기초] day14 : 파일입출력 예제(사진 복사하기)

시케 2023. 5. 22. 15:30
728x90
반응형

2023.05.22.월

사진 복사하기

기존에 있던 사진 파일을 "-복사본"이라는 이름으로 복사한다

 

예제)

package class04;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test04 {

	public static void main(String[] args) {
		final String path = "D:\\a\\resource\\";
		final String fileName = "test.jpg";
		
		final String fileCopy = "test - 복사본.jpg";
		
		try {
			FileInputStream fis = new FileInputStream(path+fileName);
			FileOutputStream fos = new FileOutputStream(path+fileCopy);

			int data;
			byte[] buff = new byte[1000]; // 한 번에 버퍼 1000씩 읽어들인다
			while ((data = fis.read(buff)) != -1) { //만약 파일 끝에 다다르면
				fos.write(buff,0,data);
			}
			
            // 파일 스트림 닫기
			fos.flush();
			fos.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			System.out.println("사진 복사 완료");
		}
	}

}

사진 복사 완료라는 문구와 함께 지정된 위치에 사진이 복사된것을 알 수있다

728x90
반응형
Comments