I about me

[Final] File I/O 본문

Java

[Final] File I/O

ssungni 2024. 6. 13. 17:44

개요

  • RAM의 한계 // 컴퓨터가 기억할 수 있는 양에는 한계가 있다. 어떤 한계?
    • 데이터 구조는 일시적임 // 즉, 컴퓨터가 잠깐만 기억하고, 컴퓨터를 꺼지면 기억을 잃는다는 한계
    • 대용량 데이터 // 많은 양의 데이터를 저장할 때 한계가 있음
  • 디스크에 관련 데이터 모음 // 그래서 데이터를 더 많이 저장하려면 디스크 같은 장기 저장 장치에 저장해야함
  • 프로그램이 디스크에서 데이터를 가져와야 함 // 즉, 한글 파일 이런 건 디스크에 저장해야해.

// 그래서 한글 파일 어떻게 관리(ex) 생성, 열기, 내용 조작)?

  • 파일 관리
    • 파일 생성 // 새로운 파일을 만듦 (ex) 객프 기말고사 정리본.hwp)
    • 파일 열기 // 전에 만든 파일을 "객프 기말고사 정리본.hwp" 열 수 있음
    • 내용 조작
      • 읽기
      • 쓰기

// 프로그램이 데이터를 쉽게 읽고 쓸 수 있도록 하는 거 다 스트림 덕분임

  • streams

    • 프로그램과 디스크 간의 인터페이스
    • 데이터가 전송되는 경로
    • 입력 스트림: 데이터를 프로그램으로 순차적으로 읽음
    • 출력 스트림: 데이터를 디스크로 순차적으로 씀
    • 프로그램은 장치의 세부 사항을 알 필요 없음
      // 즉, 프로그램은 데이터를 주고받을 때
         "어디서 저장되는지, 어떻게 저장되는지"를 알 필요 없이,
         그냥 "저장해" 혹은 "읽어와"라고만 하면 되는 거
 

Error Handling

  • I/O Exceptions
    • FileNotFoundException // 파일이 찾을 수 없을 때 발생함
      더보기
      try {
          FileInputStream file = new FileInputStream("non_existent_file.txt");
      } catch (FileNotFoundException e) {
          System.out.println("파일을 찾을 수 없습니다: " + e.getMessage());
      }
    • InterruptedIOException
      // ex) 다운로드가 진행되는 도중에 갑자기 파일이 넘 커서 멈춤 눌렀을 때 다운로드가 중단되었을 때 발생
      더보기
      try {
          InputStream in = new FileInputStream("somefile.txt");
          // 일부 입출력 작업 수행
      } catch (InterruptedIOException e) {
          System.out.println("입출력 작업이 인터럽트되었습니다: " + e.getMessage());
      }
    • IOException
      • 특정한 원인을 명시하지 않고 넓은 범위의 I/O 오류
      • 파일을 읽거나 쓸 때 다양한 입출력 오류가 발생할 때
      • 네트워크 통신 중 오류가 발생할 때
        더보기
        try {
            BufferedReader reader = new BufferedReader(new FileReader("somefile.txt"));
            String line = reader.readLine();
        } catch (IOException e) {
            System.out.println("입출력 오류가 발생했습니다: " + e.getMessage());
        }

 

// Java에서 파일 및 디렉토리를 다루는 중요한 메서드를 보자

  • import java.io.* 로 시작!
  • Some important methods
    • read → FileReader: 파일 읽기
      더보기
      import java.io.*;
      
      public class ReadFromFileExample {
          public static void main(String[] args) {
              String fileName = "input.txt";
      
              try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
                  String line;
                  while ((line = reader.readLine()) != null) {
                      System.out.println(line);
                  }
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
    • write  FileWriter: 파일에 쓰기
      더보기
      import java.io.*;
      
      public class WriteToFileExample {
          public static void main(String[] args) {
              String fileName = "output.txt";
              String content = "Hello, World!";
      
              try (FileWriter writer = new FileWriter(fileName)) {
                  writer.write(content);
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
    • delete : 파일 또는 디렉토리 삭제
      더보기
      import java.io.*;
      
      public class DeleteFileExample {
          public static void main(String[] args) {
              File file = new File("myfile.txt");
      
              if (file.delete()) {
                  System.out.println("파일 삭제 성공");
              } else {
                  System.out.println("파일 삭제 실패");
              }
          }
      }
    • listFiles: 디렉토리 내의 파일과 디렉토리 목록을 가져옴
      더보기
      import java.io.*;
      
      public class ListFilesExample {
          public static void main(String[] args) {
              File dir = new File("directoryPath");
      
              File[] files = dir.listFiles();
              if (files != null) {
                  for (File file : files) {
                      System.out.println(file.getName());
                  }
              }
          }
      }
    • mkDir: 새로운 디렉토리를 생성
      더보기
      import java.io.*;
      
      public class CreateDirectoryExample {
          public static void main(String[] args) {
              File newDir = new File("newDirectory");
      
              if (newDir.mkdir()) {
                  System.out.println("디렉토리 생성 성공");
              } else {
                  System.out.println("디렉토리 생성 실패");
              }
          }
      }
  • Example: Copy files(교수님 강노 예시임)
    import java.io.*;
    public class Copy {
    	public static void main(String[] args) throws IOException {
        	// 복사할 원본 파일 경로와 복사될 대상 파일 경로
            File inputFile = new File("f1.txt");
            File outputFile = new File("f2.txt");
            
            // 파일 입력 스트림과 출력 스트림을 선언
            FileReader in = new FileReader(inputFile);
            FileWriter out = new FileWriter(outputFile);
            
            int c;
    		while ((c = in.read()) != -1){ // 파일에서 한 문자씩 읽다가 파일 끝에 도달하면
            	out.write(c); // 끝
            }
            
            in.close(); // 입력 스트림 닫기
            out.close(); // 출력 스트림 닫기
         }
    }


  • Example 
    1) Write to a File
    2) List the contents of a Folder
    3) Tokenize file contents
    4) Using BufferedReader and BufferedWriter

 

 

 

'Java' 카테고리의 다른 글

[Final] collections  (0) 2024.06.15
[Final] Serialization  (1) 2024.06.14
[Final] Exception Handling 문제 풀이  (0) 2024.06.11
[Final] Exception  (0) 2024.06.11
[Final] Interface  (0) 2024.06.10