💡 학습 목표 바이트 단위에 기반스트림 파일 입력,출력 스트림을 함께 사용해 보자. |
시나리오 코드 1 - 기반 스트림인 파일 입력,출력 스트림을 사용
package Io.file.ch03;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class FileCopy {
public static void main(String[] args) {
// 스트림은 기본적으로 단방향이다.
// 이는 한 방향으로 데이터를 흘려보낼 수 있음이다. ↓
// 입력 스트림, 출력 스트림 두개가 필요하다.
// 파일 경로 (복사할 대상)
String sourceFilePath = "C:\\Users\\KDP\\Documents\\Lightshot\\a.zip";
// 목적지 파일
String destinationFilePath = "copy1.zip";
// 소요시간 확인
long startTime = System.nanoTime();
try (FileInputStream in = new FileInputStream(sourceFilePath);
FileOutputStream out = new FileOutputStream(destinationFilePath)) {
int data;
while ((data = in.read()) != -1) {
// 파일에 출력
out.write(data);
}
System.out.println("입력스트림 --> 출력 스트림 --> 입력 --> 출력의 반복 완료");
} catch (Exception e) {
}
long endTime = System.nanoTime();
long duration = endTime - startTime;
System.out.println("복사의 소요시간은 : " + duration);
// 소요 시간을 초 단위로 변환 --> 포맷팅
double seconds = duration / 1_000_000_000.0;
// String 클래스에 format 메서드 사용해보기
String resultFormat = String.format("소요시간은 : %.6f초 입니다. ", seconds);
// % 는 포맷 지정자의 시작
// f 지정자는 float, double 유형의 변수를 인자로 받아 처리하겠다.
System.out.println(resultFormat);
} // end of main
} // end of class
다른 방법
public class BufferedFileCopy {
public static void main(String[] args) {
// (바이트 기반 스트림을 활용)
// 기반 스트림 + 보조스트림을 활용해서
// 파일 복사 기능을 만들고
// 소요 시간을 측정하시오
// 파일 경로 (복사할 대상)
String sourceFilePath = "D:\\test\\a.zip";
String destinationFilePath = "copy1.zip";
// 소요 시간
long start = System.nanoTime();
try (FileInputStream fis = new FileInputStream(sourceFilePath);
FileOutputStream fos = new FileOutputStream(destinationFilePath);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos)) {
int data;
while ((data = bis.read()) != -1) {
bos.write(data);
}
bos.flush(); // 매번 입출력을 발생하는 것이 아니라 한번에 입출력을 사용
long end = System.nanoTime();
// 소요 시간을 초 단위로 변환 --> 포멧팅
double seconds = (end - start) / 1000000000.0;
// String 클래스의 format 메소드 사용해보기
String resultFormat = String.format("소요 시간은 : %.6f초 입니다.", seconds);
// % 는 포멧 지정자의 시작
// f 지정자는 float, double 유형의 변수를 인자로 받아 처리하겠다
System.out.println(resultFormat);
} catch (Exception e) {
e.printStackTrace(); // 파일 저장 기능 가능
}
}
}
'Java > JAVA 3 - 유용한 클래스' 카테고리의 다른 글
파일 입력 스트림(문자 기반 스트림) - 14 (0) | 2024.05.21 |
---|---|
문자 기반 스트림 - 13 (0) | 2024.05.21 |
파일 출력 스트림(바이트 기반) - 11 (0) | 2024.05.21 |
파일 입력 스트림(바이트 기반) - 10 (0) | 2024.05.21 |
표준 입출력이란? - 9 (0) | 2024.05.21 |