본문 바로가기
Java/stream

Java Stream - FileInputStream & FileOutPutStream

by S.T.Lee 2022. 11. 13.

input/output stream은 바이트 기반 입출력 클래스의 최상위 클래스이자 추상클래스. 입출력할 데이터가 os와 jvm을 거쳐 메모리에 1byte씩 전달된다.

//파일 복사하기
package lec08.fileio04.second.stream.e;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class FileIOMain {
	public static void fileCopy(File target, String destination) throws Exception {
		File destinationFile = new File(destination);
		boolean destExists = destinationFile.exists();
		if (destExists == true) {
			String showMsg = "이미 파일이 존재하여 복사할 수 없습니다.";
			throw new Exception(showMsg);
		}
		
		FileInputStream fileInputStream = new FileInputStream(target);
		FileOutputStream fileOutputStream = new FileOutputStream(destinationFile);
		
		byte[] bytes = new byte[1024];
		while (true) {
			int read = fileInputStream.read(bytes);
			if (read == -1) {
				break;
			}
			fileOutputStream.write(bytes, 0, read);
		}
		
		fileInputStream.close();
		fileOutputStream.close();
	}
	public static void main(String[] args) {
		String targetPath = "C:\\오픈할 파일 경로.txt";
		String destinationPath = "C:\\저장할 파일 경로.txt";
		
		try {
			fileCopy(new File(targetPath), destinationPath);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

'Java > stream' 카테고리의 다른 글

Java Stream - FileWriter  (0) 2022.11.13
Java Stream - FileReader  (0) 2022.11.13
Java Stream - FileOutputStream  (0) 2022.11.13
Java Stream - UseByteArray  (0) 2022.11.13
Java Stream - FileReader vs FileInputStream  (0) 2022.11.13