java

java_15_Io 패키지- 출력스트림(OutputStream)

-JUNHEOK- 2021. 10. 29. 01:52

OutputStream

바이트기반 출력스트림의 최상위 클래스로 추상클래스이다. 모든 바이트 기반 출력 스트림클래스는 이 클래스를 상속받아서 만들어진다. 

 

 

 

 

 

OutputStream 클래스에는 모든 바이트 기반 출력스트림이 기본적으로 가져야할 메서드가 정의되어 있다.

 

리턴타입 메서드 설명
void write(int b) 출력스트림으로 1바이트를 보낸다.
void write(byte[ ]  b) 출력스트림으로 주어진 바이트 배열 b의 모든 바이트를 보낸다;
void write(byte[ ] b, int off, int len) 출력스트림으로 주어진 바이트 배열 b[off]부터 len개까지의 바이트를 보낸다
void flush() 버퍼에 잔류하는 모든 바이트를 출력한다.
void close() 사용한 시스템 자원을 반납하고 출력 스트림을 닫는다. 

 

 

 

write(int b) 메서드

매개 변수로 주어진 int값으로 끝에 있는 1바이트만 출력 스트림으로 보낸다. 

 

OutputStream os = new FileOutputStream("C:/text.txt");
byte[ ] data = "ABC".getBytes();
for(int i = 0; i<data.length; i++){
	os.write(data[i]); //"A", "B", "C"를 하나씩 출력
}

 

 

write(byte[] b) 메서드

 

매개값으로 주어진 바이트배열의 모든 바이트를 출력 스트림으로 보낸다. 

OutputStream os = new FileOutputStream("C:/text.txt");
byte[ ] data = "ABC".getBytes();
os.write(data); //"ABC"모두 출력
}

 

 

write(byte[] b, int off, int len) 메서드

b[off]부터 len개의 바이트를 출력 스트림으로 보낸다. 

 

OutputStream os = new FileOutputStream("C:/test.txt");
byte[ ]  data = "ABC".getBytes();
os.write(data,1,2);  //"BC" 출력

 

public static void writeTest() {
		/*
		 * a.txt파일에 바이트단위로 쓰기
		 * 1. 목적지결정 : a.txt파일
		 * 2. 처리할 노드스트림결정: FileoutputStream
		 */
		String fileName = "a.txt";  
		FileOutputStream fos = null;
		
		 
			try {
				fos = new FileOutputStream(fileName); //새로 파일이 만들어짐
				fos.write(65);  //'A'
				fos.write(97);  //'a'
				fos.write(13); fos.write(10);  //enter 
				fos.write(49);   //'1'
				
				
			}catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		}
	}