본문 바로가기
Programming

JAVA BufferedReader와 BufferedWriter 사용법

by 하하호호 2022. 2. 18.
반응형

 

Scanner나 System.out.print() 사용해서 입출력을 만들게 되면 메모리에 상당한 부담이 가해지게 된다. 이를 방지하기 위해서 버퍼를 사용해서 입출력 효율을 올릴 수 있다. 데이터 처리양이 많을 때 유용한 기능이다.

 

BufferedReader는 Scanner의 기능을 한다. Scanner의 경우 공백도 사용가능하지만, BufferedReader를 사용할 때는 Enter만 구분자로 인식하기 때문에 추가적으로 가공을 해줘야 한다. 또한 BufferedReader에서 받아오는 데이터는 모두 String 객체이기 때문에, 형변환을 반드시 해줘야 한다.

 

BufferedWriter는 System.out.print 메소드와 일치된다. 다만 중간에 버퍼를 사용하기 때문에 더 빠르다는 차이점이 있는 것이다. 

 

Program으로 입력값이 안가고 Buffer를 사용하는데 왜 성능이 더 좋아지는 건가? 주기억장치 위에서 돌아가는 CPU의 속도는 빠르다. 외부에서 데이터를 저장하는 보조기억장치는 속도가 매우 느리다. 그 중간에서 I/O가 발생하게 되는데 이게 속도가 굉장히 느리다는게 문제점이다.

 

그래서 Buffer를 두고, 여기에 I/O 값을 모아뒀다가 한번에 옮기는게 하나씩 옮기는 것 보다 프로그램 성능이 훨씬 좋아지게 되는 것이다. 숫가락으로 물을 퍼내는 것 보다 바가지를 써서 한번에 퍼내는게 빠른것처럼 말이다.

 

 

BufferedReader Example

import java.io.*;

public class BufferedTest {
    public static void main(String[] args) throws IOException{
        try{

            
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            
            
            
            String line="";
            for(int i=1; (line=br.readLine())!=null; i++){
                if(line.indexOf(";") != -1)
                    System.out.println(i+":"+line);
            }
            br.close();


        }catch(IOException e){
            System.out.println(e.getMessage());
        }
    }
}

BufferdReader에는 readLine()를 포함해 다른 메소드들을 가지고 있다.

 

BufferedReader Method()

void close()
Closes the stream and releases any system resources associated with it.
버퍼 스트림을 닫는 메소드
Stream<String> lines()
Returns a Stream, the elements of which are lines read from this BufferedReader.
스트림 형태로 버퍼를 읽어들이는 메소드
void mark(int readAheadLimit)
Marks the present position in the stream.
현재 스트림에서 위치를 알려주는 메소드
boolean markSupported()
Tells whether this stream supports the mark() operation, which it does.
mark가 정상작동하는지 확인하는 메소드
int read()
Reads a single character.
Character 단위로 읽어오는 메소드
int read(char[] cbuf, int off, int len)
Reads characters into a portion of an array.
배열 안에서 Character 단위로 읽어오는 메소드
String readLine()
Reads a line of text.
텍스트를 읽어오는 메소드
boolean ready()
Tells whether this stream is ready to be read.
읽을 준비가 됬는지 확인 메소드
void reset()
Resets the stream to the most recent mark.
스트림 리셋 메소드
long skip(long n)
Skips characters.
캐릭터 건너뛰기 메소드

 

 

BufferedWriter는 System.out.println과 유사한 클래스다. BufferedWriter를 사용할 때는 새로운 줄 바꿈을 위해서 newLine() 메소드를 이용한다.

 

BufferedWriter Example

import java.io.*;

public class BufferedTest2 {
    public static void main(String[] args) throws IOException{
        try{

           BufferedWriter bw = new BufferedWriter(new FileWriter("BufferedWriter.txt"));
           bw.write("hellow \n");
           bw.flush();
           bw.close();


        }catch(IOException e){
            System.out.println(e.getMessage());
        }
    }
}

 

flush() 메소드는 Buffer 내에 남은 찌그레기를 모두 출력해준다. 다 쓴 Buffer는 close() 메소드로 닫아준다. BufferedWriter 클래스의 다른 메소드들은 다음과 같다.

 

BufferedWriter Example Method()

void close()
Closes the stream, flushing it first.
버퍼 스트림을 닫아준다.
void flush()
Flushes the stream.
남은 버퍼 스트림을 출력한다.
void newLine()
Writes a line separator.
줄 바꿈을 통해 출력한다.
void write(char[] cbuf, int off, int len)
Writes a portion of an array of characters.
배열의 캐릭터를 출력한다.
void write(int c)
Writes a single character.
void write(String s, int off, int len)
Writes a portion of a String.
반응형

댓글