byte 단위 입출력

5BRack·2022년 7월 7일

자바란?

목록 보기
40/42

byte 단위 입출력

  • 자바 입출력은 프로그램 기준으로 데이터가 들어오는 입력과 프로그램 외부로 나가는 출력으로 구성된다.

입출력 종류

byte 단위 입출력

  • byte 단위 입출력은 말 그대로 송수신하고자 하는 데이터를 byte 단위로 쪼개 보내고 받는 것이다.
  • InputStream 과 OutputStream 추상 클래스가 사용된다.

InputStream 상속구조

  • InputStream 추상 클래스는 byte 단위의 입력에 사용되는 최상위 추상 클래스이다.
  • InputStream 추상 클래스를 구현하는 대표적인 자식 클래스에는 FileInputStream, BufferedInputStream, DataInputStream 등이 있다.
  • 자바에서 콘솔 입력을 위해 미리 객체를 생성해 제공하는 System.in 도 이 InputStream의 추메서드를 구현한 클래스의 객체이다.

InputStream 의 주요 메서드

  • int available() - InputStream의 남은 바이트 수를 리턴
  • abstract int read() - int(4byte)의 하위 1byte에 읽은 데이터를 저장해 리턴(추상메서드)
  • int read(byte[] b) - 읽은 데이터를 byte[] b의 0번째 위치부터 저장하며, 읽은 바이트 수를 리턴
  • int read(byte[] b, int off, int len) - len 개수만큼 읽은 데이터를 byte[] b의 off 위치부터 저장
  • void close() - InputStream의 자원반환

OutputStream 상속구조

  • OutputStream 추상 클래스는 byte 단위의 출력에 사용되는 최상위 추상 클래스이다.
  • 이를 구현한 대표적인 자식 클래스 들로는 FileOutputStream, BufferedOutputStream, DataOutputStream, PrintStream 등이 있다.
  • 자바에서 콘솔 출력을 위해 미리 만들어 제공하는 객체인 System.out 도 PrintStream 타입의 객체이다.

OutputStream 의 주요 메서드

  • void flush() - 메모리 버퍼에 저장된 output stream 내보내기(실제로 출력 수행)
  • abstract void write(int b) - int(4byte)의 하위 1byte를 output 버퍼에 출력
  • void write(byte[] b) - 매개변수로 넘겨진 byte[] b의 0번째 위치부터 메모리 버퍼에 출력
  • void write(byte[] b, int off, int len) - byte[]의 off위치에서 len개를 읽은 후 출력
  • void close() - OutputStream의 자원 반환

InputStream 객체 활용

FileInputStream으로 InputStream 객체 생성

  • FileInputStream은 InputStream을 상속한 대표적인 클래스로, File의 내용을 byte단위로 읽는다.
  • FileInputStream 객체는 2가지 생성자를 이용해 생성할 수 있다.
  1. FileInputSream(File file) - 매개변수로 넘어온 file을 읽기 위한 InputStream 생성
  2. FileInputStream(String name) - 매개변수로 넘어온 name 위치의 파일을 읽기 위한 InputStream 생성
File inFile = new File("infile.txt");
InputStream fis = new FileInputStream(infile);
InputStream fis = new FileInputStream("infile.txt");

FileInputStream 데이터 입력 과정

  1. FileInputStream 객체가 생성되면, 어플리케이션 쪽으로 흐르는 빨대를 꼽은 것과 비슷하다.
    • 데이터는 읽는 것만 가능하다.
  2. read()메서드를 반복적으로 호출해 파일의 데이터를 하나씩 읽는다.
int data;
while((data=is.read())!= -1){
	System.out.println("읽은 데이터 :" + (char)data + "남은 바이트 수 :" + is.available());
}
  1. 모든 작업이 끝나면 사용했던 FileInputStream 자원을 close()메서드를 호출해 반납한다.
is.close();

OutputStream 객체 활용

  • InputStream 과정과 대치된다.

FileOutputStream으로 OutputStream 객체 생성

  • FileOutputStream은 OutputStream을 상속한 대표적인 클래스로, File의 내용을 byte단위로 출력한다.
  • FileOutputStream 객체는 4가지 생성자를 이용해 생성할 수 있다.
  1. FileOutputSream(File file) - 매개변수로 넘어온 file을 쓰기 위한 OutputStream 생성
  2. FileOutputSream(File file,boolean append) - 매개변수로 넘어온 file을 쓰기 위한 OutputStream 생성, append = true 일 때 이어쓰기, false 일때 새로 덮어쓰기 (default = false)
  3. FileOutputStream(String name) - 매개변수로 넘어온 name 위치의 파일을 쓰기 위한 OutputStream 생성
  4. FileOutputStream(String name,boolean append) - 매개변수로 넘어온 name 위치의 파일을 쓰기 위한 OutputStream 생성, append = true 일 때 이어쓰기, false 일때 새로 덮어쓰기 (default = false)
File inFile = new File("infile.txt");
OutputStream fos = new FileInputStream(infile,true);
OutputStream fos = new FileInputStream("infile.txt",true);

FileOutputStream 데이터 출력 과정

  • write() 메서드를 호출하면 실제로는 내부 메모리 버퍼에 기록된다. 따라서 실제로 출력을 하려면 flush()메서드를 호출해야 한다.
  • write() 메서드 사용 후 flush()메서드 사용을 생활화 해야 한다.
  1. FileOutputStream 객체가 생성되면, 어플리케이션 쪽으로 흐르는 빨대를 꼽은 것과 비슷하다.
    • 데이터는 쓰는 것만 가능하다.
  2. write()메서드를 반복적으로 호출해 파일의 데이터를 하나씩 내부 메모리로 보낸다.
  3. flush()메서드를 호출하여 출력을 한다.
  4. 모든 작업이 끝나면 사용했던 FileOutputStream 자원을 close()메서드를 호출해 반납한다.
OutoutStream os2 = new FileOutputStream(outFile,true);
byte[] byteArray1 = "Hello1".getBytes();
os2.write(byteArray1);
os2.write('\n');
os2.flush();
os2.close();

입출력 필터링

  • InputStream 과 OutputStream 만으로도 데이터의 입출력을 수행할 수 있지만, byte 단위로 데이터를 출력하다 보니 속도가 느리고 다양한 타입을 바로 출력할 수 없다.
  • 이를 개선할 수 있는 것이 바로 FilterInputStream 과 FilterOutputStream 이다. 이에 해당하는 클래스로는 Bufferd(Input/Output)Stream, Data(Input/Output)Stream, PrintStream 을 들 수 있다.

BufferedInputStream과 BufferedOutputStream

  • BufferedInputStream과 BufferedOutputStream은 입출력 과정에서 메모리 버퍼를 사용해 속도를 향상시키는 클래스다.
  • 쓰고자 하는 데이터를 메모리 버퍼에 기록하고, 한번에 모아 파일에 쓴다는 개념이다.
  • 하드디스크와 메모리의 쓰기 속도차이가 크기 때문에 메모리버퍼를 사용하면 엄청나게 퍼포먼스가 향상된다.

BufferedInputStream 생성

  • BufferedInputStream의 객체는 2가지 생성자를 이용해 생성한다.
  • 2가지 모두 생성자 매개변수로 InputStream을 포함하고 있는데 개념적으로 InputStream 끝에 필터로써 연결을 해주어야 하기 때문이다.
BufferedInputStream(InputStream in)
BufferedInputStream(InputStream in, int size)  //size - 버퍼의 크기를 지정
File orgfile = new File("mycat_origin.jpg");
InputStream is = new FileInputSream(orifile);
BufferedInputStream bis = new BufferedInputStream(is);

BufferedOutputStream

  • BufferedOutputStream도 2가지 생성자 중 하나를 이용해 객체를 생성할 수 있으며, 2가지 생성자 모두 OutputStream 객체를 매개변수로 받는다.
BufferedOutputStream(OutputStream os)
BufferedOutputStream(OutputStream os, int size)
File outfile = new File("mycat_origin.jpg");
OutputStream ps = new FileOutputStream(outfile);
BufferedOutputstream bos = new BufferedOutputStream(os);

DataInputStream 과 DataOutputStream

  • DataInputStream 과 DataOutputStream 은 다양한 데이터 타입으로 입출력을 지원하는 클래스이다.

DataInputStream 생성

  • DataInputStream의 객체는 다음과 같이 InputStream 객체를 매개변수로 포함하고 있는 생성자를 이용해 생성한다.
DataInputStream(InputStream in)
File datafile = new File("file1.data");
InputStream is = new FileInputStream(datafile);
DataInputStream dis = new DataInputStream(is);

DataOutputStream 생성

  • DataOutputStream의 객체 또한 2가지 생성자를 이용해 생성한다.
DataOutputStream(OutputStream out)
File datafile = new File("file1.data");
OutputStream = new FileOutputStream(datafile);
DataOutputStream dos = new DataOutputStream(os);

DataInputStream 메소드

  • boolean readBoolean() throws IOException - Stream으로부터 읽은 boolean을 반환한다.
  • byte readByte() throws IOException - Stream으로부터 읽은 byte를 반환한다.
  • char readChar() throws IOException - Stream으로부터 읽은 char를 반환한다.
  • double readDouble throws IOException - Stream으로부터 double을 반환한다.
  • float readFloat() throws IOException - Stream으로부터 float을 반환한다.
  • long readLong() throws IOException - Stream으로부터 long을 반환한다.
  • short readShort() throws IOException - Stream으로부터short를 반환한다.
  • int readInt() throws IOException - Stream으로부터 int를 반환한다.
  • void readFully(byte[] buf) throws IOException - Stream으로부터 buf 크기만큼의 바이트를 읽어 buf[]에 저장한다.
  • void readFully(byte[] buf, int off, int len) throws IOException - Stream으로부터 len 길이만큼 바이트를 읽어 buf의 off 위치에 저장한다.
  • String readUTF() throws IOException - UTF 인코딩 값을 얻어 문자열로 반환한다.
  • static String readUTF(DataInput in) throws IOException - DataInput의 수정된 UTF 인코딩 값을 얻어 문자열로 반환한다.
  • int skipBytes(int n) throws IOException - n 만큼 바이트를 skip 한다.

DataOutputStream 메소드

  • void flush() throws IOException - 버퍼를 출력하고 비운다.
  • int size() - Stream에 출력된 바이트 크기를 반환한다.
  • void write(int i) throws IOException - int 형 i 값이 갖는 1바이트를 출력한다.
  • void write(byte buf[], int index, int size) throws IOExceptionbyte - 배열 buf의 index 위치에서 size만큼 출력한다.
  • void writeBoolean(boolean b) throws IOException - boolena을 1바이트 값으로 출력한다.
  • void writeByte(int i) throws IOException - int를 4바이트 값으로 상위 바이트 먼저 출력한다.
  • void writeBytes(String s) throws IOException - 문자열을 바이트 순으로 출력한다.
  • void writeChar(int i) throws IOException - char를 2바이트 값으로 상위 바이트 먼저 출력한다.
  • void writeChars(String s) throws IOException - String 문자열을 char형으로 출력한다.
  • void writeDouble(double d) throws IOException - Double 클래스의 doubleToBits()를 사용하여 long으로 변환한 다음 long 값을 8바이트수량으로 상위바이트 먼저 출력한다.
  • void writeFloat(float f) throws IOException - Float을 floatToBits()를 사용하여 변환한 다음 int 값을 4바이트 수량으로 상위 바이트 먼저 출력한다.
  • void writeInt(int i) throws IOException - int의 상위 바이트 먼저 출력한다.
  • void writeLong(long l) throws IOException - long 형의 인자값 출력한다.
  • void writeShort(shrot s) throws IOException - short형의 인자값 출력한다.
  • void writeUTF(String s) throws IOException - UTF-8 인코딩을 사용해서 문자열을 출력한다.

필터의 조합

  • 필터는 얼마든지 조합하여 사용할 수 있다.
  • 각각의 생성자 매개변수는 InputStream 과 OutputStream이 들어가기 때문이다.
  • Stream -> Buffered -> Data 순으로 조합해야 Buffered 와 Data의 기능을 모두 사용할 수 있다.

0개의 댓글