💾 Java 파일처리 · OpenCSV · JDBC 복습 정리
🧱 [ 파일처리 (File I/O) ]
파일처리의 목적은 자바 프로그램 밖의 저장소에 데이터를 영구적으로 저장하는 것이다.
| 방향 | 역할 | 클래스 | 설명 |
|---|
| 📤 출력 | 자바 → 외부 | FileOutputStream | 자바 데이터를 외부 파일로 내보냄 |
| 📥 입력 | 외부 → 자바 | FileInputStream | 외부 데이터를 자바로 불러옴 |
⚙️ 출력(FileOutputStream)
String path = "src/Day17";
FileOutputStream fileOut = new FileOutputStream(path);
byte[] bytes = str.getBytes();
fileOut.write(bytes);
Stream은 바이트 단위로 이동하므로 문자열은 반드시 바이트 배열로 변환해야 한다.
String path = "src/Day17";
FileInputStream fileIn = new FileInputStream(path);
File file = new File(path);
byte[] bytes = new byte[(int) file.length()];
fileIn.read(bytes);
String str = new String(bytes);
| 단계 | 설명 |
|---|
| ① | 파일 객체 생성 (new File(path)) |
| ② | 파일 크기만큼 바이트배열 생성 |
| ③ | 파일에서 데이터를 읽고(read()), 문자열로 변환 |
🧩 [ MVC 패턴 순서 ]
| 단계 | 설명 |
|---|
| ① | 프로젝트 / 패키지 / 라이브러리 세팅 |
| ② | MVC 구조 클래스 선언 |
| ③ | Dto를 제외하고 싱글톤 생성 |
| ④ | Dto에 멤버변수, 생성자, 메소드 선언 (getter, setter, toString) |
| 💡 | 유효성 검사는 주로 Controller에서 수행 |
📄 [ OpenCSV 라이브러리 ]
CSV 파일을 자동으로 분리/분해하여 다루기 쉽게 만들어주는 라이브러리
🧠 [ CSVReader / CSVWriter ]
| 클래스 | 역할 | 주요 메소드 |
|---|
CSVReader | CSV 파일 읽기 | .readAll() → List<String[]> 반환 |
CSVWriter | CSV 파일 쓰기 | .writeAll(List<String[]> list) |
⚙️ [ CSV 파일 연동 메소드 ]
1️⃣ 파일 존재 여부 확인 및 생성
File file = new File(path);
if (file.exists()) {
readCSV();
} else {
file.createNewFile();
}
2️⃣ CSV 호출 메소드
FileReader fr = new FileReader(path, Charset.forName("EUC-KR"));
CSVReader csvReader = new CSVReader(fr);
List<String[]> rows = csvReader.readAll();
for (String[] row : rows) {
String content = row[0];
String writer = row[1];
BoardDto dto = new BoardDto(content, writer);
list.add(dto);
}
csvReader.close();
3️⃣ CSV 저장 메소드
FileWriter fw = new FileWriter(path);
CSVWriter csvWriter = new CSVWriter(fw);
List<String[]> data = new ArrayList<>();
csvWriter.writeAll(data);
csvWriter.close();
| 포인트 | 설명 |
|---|
| ⚙️ List<String[]> | ArrayList로 구현 가능 (List는 인터페이스) |
| 💡 메모리 누수 방지 | close() 메소드로 스트림 종료 필수 |
💾 [ JDBC (Java DataBase Connectivity) ]
자바와 데이터베이스를 연결하기 위한 표준 API
인터페이스 기반 설계 → 다형성 활용
| 인터페이스 | 역할 |
|---|
Connection | DB 연결 담당 |
PreparedStatement | SQL 실행 담당 |
ResultSet | SQL 실행 결과 조작 |
⚙️ 1️⃣ Connection (연결)
Connection conn = DriverManager.getConnection(DB_URL, DB_ID, DB_PWD);
PreparedStatement ps = conn.prepareStatement(SQL);
⚙️ 2️⃣ PreparedStatement (SQL 실행)
| 메소드 | 용도 | 반환값 |
|---|
.executeQuery() | SELECT 실행 | ResultSet |
.executeUpdate() | INSERT / UPDATE / DELETE 실행 | int |
⚙️ 3️⃣ ResultSet (결과 조작)
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String name = rs.getString("name");
int age = rs.getInt("age");
}
| 메소드 | 설명 |
|---|
.next() | 다음 레코드로 이동 |
.getXXX("컬럼명") | 현재 레코드의 컬럼값 반환 |
💻 [ JDBC 예시 코드 ]
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("[드라이버 로드 성공]");
String DB_URL = "jdbc:mysql://localhost:3306/mydb0722";
String DB_ID = "root";
String DB_PWD = "1234";
Connection conn = DriverManager.getConnection(DB_URL, DB_ID, DB_PWD);
System.out.println("[DB 연결 성공]");
String sql = "INSERT INTO test VALUES ('안녕하세요')";
PreparedStatement ps = conn.prepareStatement(sql);
ps.execute();
} catch (ClassNotFoundException e) {
System.out.println("[JDBC 드라이버 가져오기 실패]");
} catch (SQLException e) {
System.out.println("[데이터베이스 연동 실패]");
}
🧩 [ 핵심 요약 ]
| 구분 | 내용 |
|---|
| 📁 파일처리 | 외부 데이터 입출력 (FileInputStream, FileOutputStream) |
| 📄 OpenCSV | CSV 자동 파싱 / 저장 (CSVReader, CSVWriter) |
| 💾 JDBC | DB 연결, SQL 실행, 결과 처리 (Connection, PreparedStatement, ResultSet) |
💡 TIP
- 모든 I/O 및 SQL 처리는
try-catch 필수
PreparedStatement는 SQL 인젝션 방지 효과 있음
- DB 연결 정보는
properties 파일에 별도 저장 권장