Skip to content

Java_09 정리 #17

@Sam1000won

Description

@Sam1000won

파일

1. 파일 및 디렉토리 생성


  • 기능: 주어진 경로에 폴더와 파일을 생성하는 코드.
  • 주요 클래스: File

주요 메서드:

  • mkdirs() : 필요한 모든 디렉토리를 생성.
  • createNewFile() : 새로운 파일을 생성.
  • 예외 처리: 파일이나 디렉토리가 이미 존재할 경우를 처리.
File dir = new File("C:/img/temp");
if (!dir.exists()) {
    dir.mkdirs(); // 폴더 생성
}
File file = new File("C:/img/temp/test.txt");
if (!file.exists()) {
    file.createNewFile(); // 파일 생성
}

2. 파일 내용 읽기

  • 기능: 특정 파일의 내용을 읽어 콘솔에 출력하는 코드.
  • 주요 클래스: FileReader

주요 메서드:

  • read(): 파일에서 한 문자씩 읽어옴.
  • 예외 처리: 파일이 존재하지 않을 경우를 처리.
try (FileReader reader = new FileReader(file)) {
    int data;
    while ((data = reader.read()) != -1) {
        System.out.print((char) data); // 파일 내용 출력
    }
} catch (Exception e) {
    e.printStackTrace(); // 예외 처리
}

3. 파일 작성 및 출력

  • 기능: 특정 파일에 문자열을 기록하는 코드.
  • 주요 클래스: FileWriter

###주요 메서드:

  • write(): 문자열을 파일에 기록.
  • flush(): 버퍼의 내용을 파일에 강제로 기록.
  • 예외 처리: 파일 경로가 잘못되었거나, 파일이 열리지 않는 경우를 처리.
java
try (FileWriter writer = new FileWriter(file, true)) {
    writer.write("Hello, JAVA I.O."); // 파일에 문자열 작성
    writer.flush(); // 내용 강제 기록
} catch (Exception e) {
    e.printStackTrace(); // 예외 처리
}

4. 파일 복사

  • 기능: 한 파일을 다른 파일로 복사하는 코드.
  • 주요 클래스: FileInputStream, FileOutputStream

주요 메서드:

  • read(byte[]): 바이트 배열로 파일을 읽음.
  • write(byte[]): 바이트 배열을 파일에 씀.
  • 예외 처리: 파일 경로가 잘못되었거나, 읽기/쓰기 오류를 처리.
try (FileInputStream fis = new FileInputStream(src);
     FileOutputStream fos = new FileOutputStream(dst)) {
    byte[] cup = new byte[1024]; // 1KB 버퍼
    int i = 0;
    while (fis.read(cup) != -1) {
        fos.write(cup); // 파일 복사
        i++;
        System.out.println("파일 복사중..." + i);
    }
    fos.flush(); // 남은 데이터를 강제로 기록
} catch (Exception e) {
    e.printStackTrace(); // 예외 처리
}

요약

  • 각 코드는 파일 및 디렉토리에 대한 기본적인 I/O 작업을 수행.
  • 파일 및 디렉토리 생성: 존재하지 않을 경우 생성.
  • 파일 읽기: 파일의 내용을 읽어 출력.
  • 파일 작성: 문자열을 파일에 기록.
  • 파일 복사: 원본 파일의 내용을 복사본 파일로 전달.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions