Stream - Node Stream

양혜정·2024년 2월 17일
0

Begin_java

목록 보기
69/71

FileInputStream

  • 1바이트 기반 스트림
  • Node(접속점) Stream
  • 파일이 없다면 자동으로 생성되지만 폴더는 반드시 존재해야 한다.
    Ex) System.in ~~> 접속점이 키보드인 입력스트림

FileOutputStream

  • 1바이트 기반 스트림
  • Node(접속점) Stream
    Ex) System.out ~~> 모니터에 출력
    FileOutputStream ~~> 파일에 출력

예외

  • IOException ⊃ FileNotFoundException

-> FileNotFoundException : 경로 파일이 없을 경우에 대한 예외
-> IOException : 생성 시 파일 경로 자체를 잘못 적었을 경우

File file_2 = new File("ㅋ");	// 절대경로를 잘못 적은 경우

응용


- 폴더 생성하기 [ read() ]

String fileName = sc.nextLine();	// 파일의 절대경로 입력
int input = 0;		// read 의 return 타입이 int 이다.
int totalByte = 0;	// byte 수 누적 용도
try{
	FileInputStream fist = new FileInputStream(fileName);
    while((input = fist.read()) != -1) {	
    // ' -1 ' 은 없다라는 뜻으로
    // 입력한 파일의 절대경로가 없다면
    	System.out.write(input);	
    	System.out.flush();		// 모니터에 출력
    	totalByte++;
    }	// end of while------------
    fist.close();
 } catch(FileNotFoundException e) {	
 	// 파일을 못 찾는 경우 발생하는 오류
 	System.out.println(fileName + " 파일은 없습니다.");
 } catch(IOException e) { }
 System.out.println("총 " + totalByte + "byte");
 System.out.println("반복횟수 " + totalByte + "번 반복함");

- 폴더 생성하기 [ read(배열) ]

String fileName = sc.nextLine();	// 파일의 절대경로 입력
byte[] data_arr = new byte[64];
// data_arr이 한번 확인할 수 있는 byte를 64byte로 지정
int input_length = 0;		// 한번 읽는것의 길이
int totalByte = 0;	// byte 수 누적 용도
try{
	FileInputStream fist = new FileInputStream(fileName);
    while((input_length = fist.read(data_arr)) != -1) {	
    // ' -1 ' 은 없다라는 뜻으로
    // 입력한 파일의 절대경로가 없다면
    	System.out.write(data_arr, 0, input_length);	
    	System.out.flush();		// 모니터에 출력
    	totalByte += input_length;	// 총 byte 누적
        cnt++;	//반복횟수
    }	// end of while------------
    fist.close();
 } catch(FileNotFoundException e) {	
 	// 파일을 못 찾는 경우 발생하는 오류
 	System.out.println(fileName + " 파일은 없습니다.");
 } catch(IOException e) { }
 System.out.println("총 " + totalByte + "byte");
 System.out.println("반복횟수 " + cnt + "번 반복함");

- 파일 생성하기 [ read() ]

String fileName = "C:/NCS/iotestdata/result.txt";
// C:\\NCS\\iotestdata\\result.txt 와 동일
//  이때, 텍스트 이름을 제외한 폴더까지는 존재한 상태이어야 한다.!!
int input =0;
int totalByte = 0;	// byte 수 누적 용도
try{
	boolean append = false;
    FileOutputStream fost 
    		= new FileOutputStream(fileName, append);
   // append true 인 경우, fileName 안에 내용은 그대로 두고
   // 이어서 작성
   // append false 인 경우, fileName 안 내용을 지우고 작성
// FileOutputStream fost = new FileOutputStream(fileName) 은
// append 를 false 로 인식
	while((input = System.in.read()) != -1) {
    // 프로그램 종료가 아니라면
    fost.write(input);
    fost.flush();
    totalByte++;
    }	// end of while----------------
    fost.close();
    System.out.println(fileName + "에 쓰기 완료!! "
    							+ totalByte + "byte 씀");
		System.out.println("반복횟수 : " 
        						+ totalByte + "번 반복함");
} catch(FileNotFoundException e) {	// 파일이 없을 경우
	System.out.println(fileName + "파일이 없습니다.");
} catch(IOException e) { }	// end of try~catch---------

- 파일 생성하기 [ read(배열) ]

String fileName = "C:/NCS/iotestdata/result.txt";
// C:\\NCS\\iotestdata\\result.txt 와 동일
//  이때, 텍스트 이름을 제외한 폴더까지는 존재한 상태이어야 한다.!!
byte[] data_arr = new byte[10];
// 한번 읽을 수 있는 크기를 10byte 로 설정
int input_length =0;	// 한번 흡인한 실제 크기를 나타내는 용도
int totalByte = 0;	// byte 수 누적 용도
int cnt = 0;		// while 문의 반복횟수를 알기 위한 것
try{
	boolean append = false;
    FileOutputStream fost 
    		= new FileOutputStream(fileName, append);
   // append true 인 경우, fileName 안에 내용은 그대로 두고
   // 이어서 작성
   // append false 인 경우, fileName 안 내용을 지우고 작성
// FileOutputStream fost = new FileOutputStream(fileName) 은
// append 를 false 로 인식
	while((input_length = System.in.read(data_arr)) != -1) {
    // 프로그램 종료가 아니라면
    fost.write(data_arr, 0, input_length);
    fost.flush();
    totalByte += input_length;
    cnt++;
    }	// end of while----------------
    fost.close();
    System.out.println(fileName + "에 쓰기 완료!! "
    							+ totalByte + "byte 씀");
		System.out.println("반복횟수 : " 
        						+ cnt + "번 반복함");
} catch(FileNotFoundException e) {	// 파일이 없을 경우
	System.out.println(fileName + "파일이 없습니다.");
} catch(IOException e) { }	// end of try~catch---------

- 파일 복사하기

String src_fileName = sc.nextLine();	// 원본파일 절대경로
String target_fileName = sc.nextLine();	// 복사할 위치 경로
byte[] data_arr = new byte[1024];	// 1024byte = 1kb
int input_length = 0;
int totalByte = 0;	// byte 수 누적용도
int cnt = 0;		// while 문의 반복횟수를 알기위한 것
try{
	// ==== 용량 제한 두기 ==== //
	File src_file = new File(src_fileName);
    long src_file_size = src_file.length();	// 파일의 크기
    long max_size = 1024*1024*10;	// 1kb * 1kb = 1mb 
    if(src_file_size > max_size) {	
    // 원본 파일의 크기가 초과한 경우
    	sc.close();
        return;	// main() 메소드 종료
    }
    
	FileInputStream fist 
    	= new FileInputStream(src_fileName);	// 절대경로
    FileOutputStream fost
    	= new FileOutputStream(target_fileName); // 목적경로
    while((input_length = fist.read(data_arr)) != -1) {
    	fost.write(data_arr, 0, input_length);
        fost.flush();
        totalByte += input_length;
        cnt++;	// 반복횟수
   	}	// end of while----------------------------------
    fist.close();
    fost.close();
    System.out.println(target_fileName + "에 쓰기 완료!! " 
    							+ totalByte + "byte 씀");
		System.out.println("반복횟수 : " + cnt + "번 반복함");
} catch (FileNotFoundException e) {	// 파일이 없을 경우
} catch (IOException e) { }	// end of try~catch----------

정리

my.day20.a.io
-> Stream구분, FileInputStream_main_05, FileInputStream_main_06, FileInputStream_main_07, FileInputStream_main_08, FileCopy_main_09, FileCopy_main_10

0개의 댓글

관련 채용 정보