시작하기무료로 시작하기

메모 작성과 읽기

이제 파일을 만들 수 있으니 실제 내용을 추가해 보겠습니다. 텍스트 파일에 짧은 메모를 작성한 뒤, 제대로 저장되었는지 다시 읽어 확인할 거예요. 이는 어떤 메모 앱에서도 핵심 기능입니다.

필요한 java.io의 모든 패키지는 미리 임포트되어 있습니다.

이 연습은 강의의 일부입니다

Java의 입력/출력과 스트림

강의 보기

연습 안내

  • "note.txt"라는 파일에 텍스트 "Start from the beginning"을(를) 작성하세요.
  • "note.txt"에 대해 append 모드의 FileWriterfwAppendMode라는 이름으로 생성하세요.
  • 기존 내용을 덮어쓰지 않고 텍스트 " Add to the end"를 파일에 추가하세요.
  • FileReader를 사용해 파일의 내용을 한 글자씩 읽어 콘솔에 표시하세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

class FileReadWrite {

    public static void main(String[] args) {
        try {
            FileWriter fw = new FileWriter("note.txt");
            // Write "Start from the beginning" to the file
            fw.____("Start from the beginning");
            fw.close();

            // Create a FileWriter in append mode
            FileWriter fwAppendMode = new ____("note.txt", ____);

            // Add " Add to the end" to the end of file
            fwAppendMode.____(" Add to the end");
            fwAppendMode.close();

            FileReader fr = new FileReader("note.txt");
            int character;
            
            // Read the file content character by character
            while ((character = fr.____()) != -1) {
                System.out.print((char) character);
            }
            fr.close();
        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}
코드 편집 및 실행