-
14. 파일 입출력멋사 부트캠프/Java 프로그래밍 2025. 3. 19. 17:03
1. 입출력 스트림 작업 방식
Java IO (입출력, Stream 기반)
- 소량의 데이터 처리에 적합
- 동기 방식 (Blocking IO) → 데이터를 읽거나 쓸 때 해당 작업이 끝날 때까지 대기
- 단일 처리 (Single-thread 기반)
- 단방향 스트림 (InputStream / OutputStream)
- 바이트 스트림과 문자 스트림을 사용하여 데이터 처리
- 예제: FileInputStream, FileOutputStream, BufferedReader, BufferedWriter
Java NIO (New IO, Channel 기반)
- 대량의 데이터 처리에 적합
- 비동기 방식 (Non-blocking IO) → 하나의 쓰레드가 여러 작업을 처리 가능
- 다중 처리 (Multi-thread 기반 가능)
- 양방향 스트림 (Channel을 이용한 데이터 송수신 가능) → 버퍼 기반으로 동작
- 버퍼(Buffer) 기반으로 데이터 처리
- 예제: FileChannel, SocketChannel, Selector, Files, Path
2. bufferedOutputStream / bufferedInputStream 처리과정
파일 → 읽어온다(FileInputStream) → 버퍼에 담는다(BufferedInputStream ) → read()
FileInputStream 한 바이트씩 직접 읽음 → 속도 느림 BufferedInputStream 버퍼를 사용해 여러 바이트를 한 번에 읽음 → 속도 빠름 (FileInputStream 필요) FileOutputStream 한 바이트씩 직접 씀 → 속도 느림 BufferedOutputStream 버퍼를 사용해 여러 바이를 한 번에 씀 → 속도 빠름 (FileOutputStream 필요) ⇒ new BufferedInputStream(new FileInputStream(new File("a.txt")));
*) .txt, .csv/.tsv, .xml, .json, .sql ⇒ 서로 변환하면서 읽고 쓸 수 있어야 함.
주요 메서드 : read(), read(byte[] b), write(), write( byte[] b), flush()...
예제)
//파일 읽기 public class BufferedInputStreamExample { public static void main(String[] args) { //try-with-resources 사용하면 finally->close() 생략 가능 //BufferedInputStream은 AutoCloseable을 구현 -> 자동 close 호출. try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream("example.txt"))){ int data; while ((data = bis.read()) != -1) { System.out.print((char) data); // 문자로 변환해서 출력 } } catch (IOException e) { e.printStackTrace(); } } } //파일 쓰기 public class BufferedOutputStreamExample { public static void main(String[] args) { String data = "Hello, BufferedOutputStream!"; // 저장할 문자열 try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("output.txt"))) { bos.write(data.getBytes()); // 문자열을 바이트 배열로 변환 후 저장 bos.flush(); // 버퍼에 남아있는 데이터 강제 저장 System.out.println("파일에 데이터가 성공적으로 저장되었습니다."); } catch (IOException e) { e.printStackTrace(); } } }
3. Serializable (직렬화)
네트워크로 객체/파일 데이터 자료 전송을 하려면 패킷으로 전달해야 하고 그 근간 단위가 Byte이다.
즉, 직렬화는 바이트 스트림으로 변환하여 전송 및 저장하는 과정이고, 역직렬화는 바이트 스트림->객체로 변환하는 과정.
Person person = new Person("Alice", 25); // 직렬화 (객체 -> 파일) try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) { oos.writeObject(person); System.out.println("직렬화 완료"); } catch (IOException e) { e.printStackTrace(); } // 역직렬화 (파일 -> 객체) try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) { Person deserializedPerson = (Person) ois.readObject(); System.out.println("역직렬화된 객체: " + deserializedPerson); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); }
이 때, Person 클래스는 Serializable을 Implements 해야 한다.
(안할 시 받은 측에서 디코딩[역직렬화]이 제대로 수행되지 않음 -> "InvalidClassException" 같은 오류가 발생)
주요 메서드 : writeInt(int v), writeObject(Object obj), Object readObject(), int readInt()....
4. NIO 패키지 파일 처리
1) Files
파일과 디렉터리를 다룰 수 있는 다양한 정적(static) 메서드를 제공하는 유틸리티 클래스입니다.
→ 파일 생성, 삭제, 복사, 이동, 읽기, 쓰기 등의 기능을 수행합니다.→ Path 인터페이스, Paths 클래스, StandardOpenOption 클래스와 같이 사용된다.
✅ Files.createFile(path) → 파일이 존재하지 않으면 새로 생성
✅ Files.delete(path) → 파일 삭제✅ Files.createDirectory(path) → 디렉터리 생성
✅ Files.delete(path) → 디렉터리 삭제 (비어 있어야 함)✅ Files.write(path, byte[]) → 파일에 데이터 저장 (기본적으로 덮어씀)
✅ Files.readAllLines(path, Charset) → 파일의 모든 줄을 List<String>으로 반환
✅ Files.copy(source, target, 옵션) → 파일 복사
✅ Files.move(source, target, 옵션) → 파일 이동 (이름 변경도 가능)
✅ Files.size(path) → 파일 크기 반환
✅ Files.getLastModifiedTime(path) → 마지막 수정 시간 반환
✅ Files.isDirectory(path) → 파일이 디렉터리인지 확인2) Path, Paths
Paths.get() 메서드를 사용하여 문자열 경로를 Path 객체로 변환하여 사용
3) 디렉토리/파일 탐색 클래스 (FileVisitor, SimpleFileVisitor)
4) File CRUD 클래스
5) ByteBuffer, Channel 관련 클래스 (네트워크 파일 전송 시 활용)
6) StandardOption
Enum 클래스 -> 자바에서 상수(static final)을 정의할 때 사용하는 특수한 클래스
'멋사 부트캠프 > Java 프로그래밍' 카테고리의 다른 글
15. Thread (0) 2025.04.14 13. Constructor (생성자 참조 구문) (0) 2025.03.14 12. Lambda (0) 2025.03.14 11. 익명 클래스 & Functional 인터페이스 (0) 2025.03.14 10. Annotation (0) 2025.03.14