Java 주요 클래스

알비레오·2025년 3월 31일

자바

목록 보기
12/17

Connection(JDBC)

데이터베이스와 연결을 관리하는 객체

주요 메서드
1. createStatement(): SQL 쿼리를 실행하기 위한 Statement 객체를 생성합니다.
2. prepareStatement(String sql): 파라미터화된 SQL 쿼리를 실행하기 위한 PreparedStatement 객체를 생성합니다.
3. commit(), rollback(): 트랜잭션을 커밋하거나 롤백합니다.
4. close(): 연결을 닫고 리소스를 해제합니다.

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
conn.close();

Statement(JDBC)

SQL 쿼리를 실행하는 객체

주요 메서드
1. executeQuery(String sql) : SELECT 쿼리를 실행하고 결과를 ResultSet으로 반환
2. executeUpdate(String sql) : INSERT, UPDATE, DELETE 쿼리를 실행하고 영향을 받은 행 수를 반환
3. close() : Statement 객체를 닫고 리소스를 해제

Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
while (rs.next()) {
    System.out.println(rs.getString("name"));
}
stmt.close();

Properties

키-값 형태의 데이터를 저장하고 관리하는 클래스
주로 설정 파일(config.properties)을 읽고 처리하는 데 사용

주요 메서드
1. load(InputStream inStream) : 설정 파일에서 데이터를 읽어옴
2. getProperty(String key) : 특정 키에 해당하는 값을 가져옴
3. setProperty(String key, String value) : 키와 값을 설정함

Properties props = new Properties();
props.load(new FileInputStream("config.properties"));
String dbUrl = props.getProperty("db.url");
System.out.println("Database URL: " + dbUrl);

ClassLoader

클래스 파일이나 리소스를 동적으로 로드하는 역할을 함

주요 메서드
1. getResource(String name) : 특정 리소스의 URL을 가져옴
2. loadClass(String name) : 클래스 이름을 기반으로 클래스를 로드함

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader.getResource("config.properties");
System.out.println(resource);

ResultSet(JDBC)

SQL SELECT 쿼리 결과를 행과 열 형태로 저장하고 처리하는 객체

주요 메서드
1. next() : 커서를 다음 행으로 이동하며, 더 이상 행이 없으면 false를 반환함
2. getString(String columnLabel), getInt(int columnIndex) : 현재 행에서 데이터를 읽음

ResultSet rs = stmt.executeQuery("SELECT id, name FROM users");
while (rs.next()) {
    System.out.println(rs.getInt("id") + ": " + rs.getString("name"));
}

DateFormat

날짜와 시간을 특정 형식으로 변환하거나 문자열로 표현된 날짜를 파싱하느 데 사용

주요 메서드
1. format(Date date) : 날짜를 지정된 형식의 문자열로 변환
2. parse(String source) : 문자열을 날짜 객체로 변환

DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = df.format(new Date()); // 현재 날짜를 "yyyy-MM-dd" 형식으로 변환
Date parsedDate = df.parse("2025-03-31");     // 문자열을 Date 객체로 변환
System.out.println(formattedDate);

OutputStream

데이터를 바이트 단위로 출력하기 위한 추상 클래스
파일, 네트워크 등 다양한 출력 대상에 데이터를 전달할 수 있음

주요 메서드
1. write(int b) 또는 write(byte[] b) : 데이터를 출력 스트림으로 씀
2. flush() : 버퍼에 있는 데이터를 출력 대상으로 즉시 전달

OutputStream os = new FileOutputStream("output.txt");
os.write("Hello, World!".getBytes());
os.flush();
os.close();

BufferedWriter

문자 기반 데이터를 효율적으로 쓰기 위해 버퍼링 기능을 제공하는 클래스
주로 파일 쓰기에 사용됨

주요 메서드
1. write(String s) : 문자열을 출력 스트림에 씀
2. newLine() : 줄바꿈 문자를 추가함

BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
writer.write("Hello, World!");
writer.newLine(); // 줄바꿈 추가
writer.close();

InputStreamReader

바이트 기반 입력 스트림을 문자 기반 입력 스트림으로 변환하는 데 사용
주로 파일이나 네트워크에서 데이터를 읽음

InputStreamReader reader = new InputStreamReader(new FileInputStream("input.txt"), "UTF8");
int data;
while ((data = reader.read()) != -1) {
    System.out.print((char)data);
}
reader.close();

BufferedReader

문자 기반 입력 스트림을 버퍼링하여 효율적으로 데이터를 읽는 클래스
주로 파일이나 콘솔 입력을 처리할 때 사용됨

주요 메서드
1. readLine() : 한 줄의 데이터를 읽어 문자열로 반환
2. read(char[] cbuf, int off, int len) : 특정 크기의 문자 배열에 데이터를 읽음
3. close() : 스트림을 닫아 리소스를 해제

BufferedReader br = new BufferedReader(new FileReader("input.txt"));
String line;
while ((line = br.readLine()) != null) {
    System.out.println(line);
}
br.close();

StringBuffer

문자열을 수정할 수 있는 객체를 제공하며, 문자열 추가, 삭제, 변경 작업에 적합
String과 달리 뮤터블(mutable)하며, 스레드 안전

주요 메서드
1. append(String s) : 문자열을 추가
2. insert(int offset, String s) : 지정된 범위의 문자열 삭제
3. reverse() : 문자열을 뒤집음

StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
sb.reverse();
System.out.println(sb); // 출력: "dlroW olleH"

HttpURLConnection

HTTP 프로토콜을 사용하여 웹 서버와 통신하는 클래스
GET, POST 요청 등을 처리할 때 사용

주요 메서드
1. setRequesetMethod(String method) : 요청 방식 설정(GET, POST 등)
2. getResponseCode() : HTTP 응답 코드 반환
3. getInputStream() : 서버 응답 데이터를 읽기 위한 입력 스트림 반환

URL url = new URL("http://example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
    System.out.println(line);
}
br.close();
conn.disconnect();

FileOutputStream

바이트 단위로 데이터를 파일에 쓰는 데 사용되는 클래스
주로 이미지, PDF 같은 바이너리 데이터를 처리할 때 사용됨

주요 메서드
1. write(Byte[] b) : 바이트 배열 데이터를 파일에 기록
2. write(int b): 단일 바이트를 파일에 기록

FileOutputStream fos = new FileOutputStream("output.txt");
fos.write("Hello World".getBytes());
fos.close();

OutputStreamWriter

문자 데이터를 바이트 데이터로 변환하여 출력하는 클래스
주로 파일 쓰기 작업에서 사용됨

주요 메서드
1. write(String str) : 문자열 데이터를 출력 스트림으로 씀
2. flush() : 버퍼에 있는 데이터를 출력 스트림으로 전달

OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("output.txt"), "UTF-8");
osw.write("안녕하세요!");
osw.flush();
osw.close();

NodeList

XML 문서 내 노드들의 집합을 표현하는 인터페이스
DOM에서 사용됨

주요 메서드
1. item(int index) : 특정 인덱스의 노드를 반환
2. getLength() : 노드 리스트의 길이를 반환

NodeList nodeList = document.getElementsByTagName("element");
for (int i = 0; i < nodeList.getLength(); i++) {
    Node node = nodeList.item(i);
    System.out.println(node.getTextContent());
}

DocumentBuilderFactory

XML 문서를 DOM 객체로 파싱하기 위한 팩토리 클래스

주요 메서드
1. newInstance() : 새로운 팩토리 인스턴스를 생성
2. newDocumentBuilder() : DOM 파서를 생성

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("input.xml"));

DocumentBuilder

XML 문서를 DOM 객체로 파싱하는 클래스

주요 메서드
1. parse(File file) : 파일을 파싱하여 DOM 객체를 생성

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("input.xml"));

Document

XML 문서를 DOM 형식으로 표현하는 클래스
XML 요소와 속성에 접근할 수 있음

DatabaseConnectionClass

데이터베이스 연결을 관리하고, SQL 쿼리를 실행하기 위한 JDBC 기반의 유틸리티 클래스
애플리케이션에서 데이터베이스와 상호작용하는 데 필요한 연결과 쿼리 실행을 처리
주요 역할을 데이터베이스 연결을 설정하고 SQL 작업을 수행한 뒤 자원을 정리하는 것

주요 역할
1. 데이터베이스 연결 관리

  • JDBC를 사용하여 데이터베이스와 연결을 설정함
  • 연결 정보를 외부 설정 파일(config.properties)에서 가져옴
  1. SQL 쿼리 실행 지원
  • Statement 객체를 생성하여 SQL 쿼리를 실행할 수 있도록 제공함
  1. 자원 정리
  • 데이터베이스 연결과 쿼리 실행 객체를 닫아 리소스를 해제함

주요 메서드
1. connectDB()

  • 역할
    데이터베이스에 연결하고, Connection 및 Statement 객체를 초기화함
  • 동작
  1. 외부 설정 파일(config.properties)에서 DB 접속 정보를 읽어옴
  2. JDBC 드라이버를 로드하고, DriverManager를 통해 DB에 연결함
  3. 연결된 DB에서 SQL 쿼리를 실행할 수 있도록 Statement 객체를 생성함
  • 예외 처리
    드라이버가 없거나 연결 실패 시 예외를 처리하고 로그를 기록함
  1. disconnectDB()
  • 역할
    데이터베이스와의 연결을 닫고, 자원을 정리함
  • 동작
    Statement와 Connection 객체를 닫아 리소스를 해제함
  • 예외 처리
    닫는 과정에서 발생하는 예외를 처리하고 로그를 기록함
  1. getDBStatement()
  • 역할
    초기화된 Statement 객체를 반환하여 외부에서 SQL 쿼리를 실행할 수 있도록 지원함
  • 동작
    클래스 내부의 dbStatement 필드를 변환함

0개의 댓글