자바에서 파일을 읽는 다양한 방법 중 read()와 read(byte[] b, int offset, int len) 메소드의 차이점을 비교해보고, 더 효율적인 방법을 선택하는 것이 중요합니다.
read() 메소드와 read(byte[] b, int offset, int len) 메소드 비교
효율성:
- read() 메소드는 한 번에 한 바이트씩 읽기 때문에, I/O 작업이 많이 발생하여 성능이 저하될 수 있습니다.
- read(byte[] b, int offset, int len) 메소드는 한 번에 여러 바이트를 읽을 수 있어 I/O 작업의 횟수를 줄여 성능이 향상됩니다.
버퍼 사용:
- read() 메소드는 읽은 데이터를 배열이나 스트링에 저장하려면 추가적인 작업이 필요합니다.
- read(byte[] b, int offset, int len) 메소드는 바이트 배열에 데이터를 한꺼번에 저장할 수 있어 후속 처리가 훨씬 간편하고 효율적입니다.
public class LowerCaseInputStream extends FilterInputStream{
protected LowerCaseInputStream(InputStream in) {
super(in);
}
public int read() throws IOException{
int c = in.read();
return (c == -1? c : Character.toLowerCase((char)c));
}
public int read(byte[] b, int offset, int len) throws IOException{
int result = in.read(b, offset, len);
for(int i = offset; i < offset + result; i ++) {
b[i] = (byte)Character.toLowerCase((char)b[i]);
}
return result;
}
}
public class testMain{
public static void main(String[] args) throws IOException{
int c;
try {
String inFilePath = "test/test.txt";
String outFilePath = "test/write2.txt";
InputStream in = new LowerCaseInputStream(new BufferedInputStream(new FileInputStream(inFilePath)));
OutputStream out = new FileOutputStream(outFilePath);
/*
while((c = in.read()) >= 0) {
System.out.print((char)c);
}
*/
byte[] buffer = new byte[1024];
while ((c = in.read(buffer, 0, buffer.length)) != -1) {
System.out.write(buffer, 0, c);
out.write(buffer, 0, c);
}
in.close();
out.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
결론
- 효율성: 한 번에 여러 바이트를 읽음으로써 I/O 작업을 줄입니다.
- 가독성: 코드가 더 간결하고 명확합니다.
- 유지보수성: 데이터 처리 로직이 간단해져 유지보수하기 쉽습니다.
따라서 read()메소드 보다는 read(byte[] b, int offset, int len) 메소드를 사용하는 것이 더 바람직합니다.
참고
- 자바 표준 라이브러리 문서:
- InputStream 클래스의 read()
- InputStream 클래스의 read(byte[] b, int off, int len)
'Java' 카테고리의 다른 글
| Java 람다 (0) | 2024.08.10 |
|---|---|
| JAVA SOLID 개념 (0) | 2024.07.17 |
| String vs StringBuilder 속도 비교 (0) | 2024.03.23 |
| Java에서 Json(Object, Array) 다루기 (0) | 2024.03.01 |
| Java 개행처리 (0) | 2024.02.28 |