Byte 단위 입출력 심화
- 입출력 클래스는 클래스의 이름이 InputStream이나 0utputStream으로 끝난다
- 파일 읽을 때는 FileInputStream으로 읽게 된다
- FileInputStream안에 있는 read()메소드는 기본적으로 1byte 단위로 읽게 된다
buffer를 사용하지 않고 읽으면 stream은 512바이트를 가져와서 1바이트를 읽는 과정을 거치기에 매우 비효율적이다
buffer를 사용하면 512바이트씩 가져와서 읽기 때문에 매우 효율적이다
ex) 1024명의 승객을 512인승 비행기에 1명만 태우고 여러번 왔다갔다 하는 것보다 512명을 다 태우고 2번 반복하는게 더 효과적인 것과 같은 맥락
///파일을 빨리, 내가 원하는 byte만큼 읽어오는 코드
public class ByteIOExam1 {
public static void main(String[] args){
//메소드가 시작된 시간을 구하기 위함
long startTime = System.currentTimeMillis();
FileInputStream fis = null; ///파일로부터 읽어오기 위한 객체
FileOutputStream fos = null; ///파일에 쓸 수 있게 해주는 객체
try {
fis = new FileInputStream("src/javaIO/exam/ByteExam1.java");
fos = new FileOutputStream("byte.txt");
int readCount = -1;
byte[] buffer = new byte[512]; ///원하는 크기의 데이터 생성
while((readCount = fis.read(buffer))!= -1){
fos.write(buffer,0,readCount);
///더 이상 읽어들일 것이 없을때 -1을 return
///write(String s, int start, int len)의 구조를 가지고 있는데,
///s의 start지점부터 len 길이만큼 데이터를 출력시키겠다는 의미를 가지게 된다
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//메소드가 끝났을때 시간을 구하기 위함.
long endTime = System.currentTimeMillis(); ///현재 시간을 롱타입으로 반환하다
//메소드를 수행하는데 걸린 시간을 구할 수 있음.
System.out.println(endTime-startTime);
}
}
*위 게시물은 프로그래머스<자바중급>강좌를 보고 작성하였습니다*
'JAVA' 카테고리의 다른 글
JAVA(2022.05.29) - char 단위 입출력(Console, File) (0) | 2022.05.29 |
---|---|
JAVA(2022.05.28) - 다양한 타입의 출력(DataOutputStream, DataInputStream) (0) | 2022.05.28 |
JAVA(2022.05.26) - Byte단위 입출력 (0) | 2022.05.26 |
JAVA(2022.05.25)-자바IO (0) | 2022.05.25 |
JAVA(2022.05.24)-java.time패키지 (0) | 2022.05.24 |