Java

[자바의 다양한 기능들] 7.4 바이트 단위 입출력 스트림(OutputStream)

코딩펭귄 2024. 1. 17. 00:18

OutputStream

  • 바이트 단위 출력 스트림 최상위 추상 클래스
  • 많은 추상 메서드가 선언되어 있고 이를 하위 스트림이 상속받아 구현함
주요 하위 클래스

FileOutputStream  :  파일에서 바이트 단위로 자료를 씀

ByteArrayOutputStream byte  :  배열 메모리에서 바이트 단위로 자료를씀

FilterOutputStream  :  기반 스트림에서 자료를 쓸 때 추가 기능을 제공하는 보조 스트림의 상위 클래스

 

주요 메서드

int write()  :  한 바이트를 출력

int write(byte b[]) b[]  :  크기의 자료를 출력

int write(byte b[], int off, int len) : b[] 배열에 있는 자료의 off 위치부터 len 개수만큼 자료를 출력

void flush()  :  출력을 위해 잠시 자료가 머무르는 출력 버퍼를 강제로 비워 자료를 출력

void close()  :  출력 스트림과 연결된 대상 리소스를 닫음. 출력 버퍼가 비워짐 (출력스트림은 close할때 flush가 동시호출됨)

 

flush() 와 close() 메서드

  • 출력 버퍼를 비울때 flush() 메서드를 사용
  • close() 메서드 내부에서 flush()가 호출되므로 close()메서드가 호출되면 출력 버퍼가 비워짐
  • fulsh()는 file보다는 다른 소켓이나 네트워크할때  쓰임

 

 

FileOutputStream 예제

1) 파일에 한 바이트씩 쓰기

    public class FileOutputStreamTest1 {

	public static void main(String[] args) {
		
        //InputStream의 경우 읽으려는 파일이 없으면 file not found exception이 떨어지지만, 
        //OutputStream의 경우 없으면 파일을 만들어준다
        //default 는 overwrite 임 (한번 써도, 다시쓰게되면 처음부터 쓴다, 이어쓰고싶다면 두번째변수(파일이름 옆)에 true 써준다) )
		
        try(FileOutputStream fos = new FileOutputStream("output.txt")){ //java7부터 제공
			fos.write(65);  //A
			fos.write(66);  //B
			fos.write(67);  //C
            
		}catch(IOException e) {
			System.out.println(e);
		}
		System.out.println("출력이 완료되었습니다.");
        
        // -> output.txt 파일에 ABC 가 생긴다
	}
}

 

2) byte[] 배열에 A-Z 까지 넣고 배열을 한꺼번에 파일에 쓰기

public class FileOutputStreamTest2 {

	public static void main(String[] args) throws IOException {
		
		FileOutputStream fos = new FileOutputStream("output2.txt",true);
		
        try(fos){ //java 9 부터 제공되는 기능
		
			byte[] bs = new byte[26];// 26개짜리 배열 생성
            
			byte data = 65;        //'A' 의 아스키 값
			for(int i = 0; i < bs.length; i++){  // A-Z 까지 배열에 넣기
				bs[i] = data++;  //값을 넣고나서 증가, 반복하는 형태
			}
			
			fos.write(bs);  //배열 한꺼번에 출력하기
            
		}catch(IOException e) {
			e.printStackTrace();
		}
		System.out.println("출력이 완료되었습니다.");
	}
    // > A부터 Z까지 output.txt파일에 출력됨
}

 

3) byte[] 배열의 특정 위치에서 부터 정해진 길이 만큼 쓰기

public class FileOutputStreamTest3 {

	public static void main(String[] args) {
		 
		try(FileOutputStream fos = new FileOutputStream("output3.txt", true)
		{
		
			byte[] bs = new byte[26];
			byte data = 65;     //'A' 의 아스키 값
			for(int i = 0; i < bs.length; i++){  // A-Z 까지 배열에 넣기
				bs[i] = data++;
			}
            
			fos.write(bs, 2, 10);   // 배열의 2 번째 위치부터 10 개 바이트 출력하기 (즉, C부터 씀)
		
        }catch(IOException e) {
			System.out.println(e);
		}
		System.out.println("출력이 완료되었습니다.");
	}
    // CDEFGHIJKL 이 output.txt파일에 출력됨
    // "output3.txt", true 라고 설정해줬기 때문에, 반복해서 실행하면  CDEFGHIJKLCDEFGHIJKL 이렇게 이어짐
}