[자바의 신] 26장 파일에 있는 것을 읽고 쓰려면 아이오를 알아야죠

한지연·2023년 4월 30일
0

📘 IO(Input과 Output)

  • 입력과 출력을 통칭하는 용어
  • 파일에 읽거나 저장할 일이 있을 때, 다른 서버나 디바이스로 보낼 일이 있을 때 사용

📚 File

File

  • 파일 및 경로 정보를 통제하기 위한 클래스
  • 클래스의 이름은 File이지만 파일의 경로 정보도 포함
  • 정체가 불분명하고, 심볼릭 링크와 같은 유닉스 계열의 파일에서 사용하는 몇몇 기능을 제대로 제공하지 못함
  • 객체를 생성하여 데이터 처리

Files

  • 모든 메소드가 static으로 선언되어 별도의 객체 생성없이 사용
  • File 클래스에 있는 메소드들을 대체하여 제공

◼︎ 경로와 상태 확인

public class PracticeFile {
    public static void main(String[] args) {
        PracticeFile file = new PracticeFile();
        
        String path = "/Users/hanjiyeon/Desktop/practice";
        
        file.isPath(path);
        
    }

    public void isPath(String pathName){
        File file = new File(pathName);
        System.out.println(pathName + " is exist = " + file.exists());
    }
}

◼︎ 디렉토리 만들기

public class PracticeFile {
    public static void main(String[] args) {

        String path2 = "/Users/hanjiyeon/Desktop/practice2";
        file.createDir(path2);
        file.isDir(path2);

    }

    public void createDir(String pathName){
        File file = new File(pathName);
        System.out.println("Create " + pathName + " result = " + file.mkdir());
    }
    
    public void isDir(String pathName){
        File file = new File(pathName);
        System.out.println(pathName + " is Directory? = " + file.isDirectory());
        System.out.println(pathName + " is File? = " + file.isFile());
    }
}
  • mkdir(): 디렉토리 하나 만듦
  • mkdirs(): 여러 개의 하위 디렉토리 만듦
  • isDirectory(): File 객체가 경로인지 확인
  • isFile(): File 객체가 하나의 file인지 확인

◼︎ File Class 이용하여 파일 처리하기

public class ManageFile {
    public static void main(String[] args) {
        ManageFile file = new ManageFile();
        String pathName = "/Users/hanjiyeon/Desktop/practice";
        String fileName = "practice.txt";
        file.createFile(pathName, fileName);

    }
    public void createFile(String pathName, String fileName){
        File file = new File(pathName, fileName);
        try {
            System.out.println("is Created ? = " + file.createNewFile()); // true
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    
    public void getFileInfo(File file) throws IOException {
        System.out.println("Absolute Path:" + file.getAbsolutePath());
        System.out.println("Absolute Path:" + file.getAbsoluteFile());
        System.out.println("Absolute Path:" + file.getCanonicalPath());
        System.out.println("Absolute Path:" + file.getCanonicalFile());
    }
    
    
    
}

createNewFile(): IOException을 던지기 때문에 try-catch 안에 사용 해야함
...Path(): 경로 String 리턴
...File(): File 객체 리턴

◼︎ 디렉토리에 있는 목록을 살펴보기 위한 list 메소드들

    public static void main(String[] args) {

        File file2 = new File(pathName);

        /* list method */

        File[] files = File.listRoots();
        String[] list = file2.list();
        String[] list2 = file2.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith("txt");
            }
        });
        File[] fileList = file2.listFiles();
        File[] fileList2 = file2.listFiles(new FileFilter() {
            @Override
            public boolean accept(File path) {
                return path.isFile();
            }
        });

        File[] fileList3 = file2.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith("txt");
            }
        });
    }

listRoots(): 루트 디렉토리 목록 File[] 리턴
list(): 현재 디렉토리에 있는 목록 String[] 리턴
list(FileNameFilter filter): 조건에 맞는 목록만 String[] 리턴
listFiles(): 현재 디렉토리 하위에 있는 목록 File[] 리턴
listFiles(FileNameFilter filter): 조건에 맞는 목록만 File[] 리턴
listFiles(FileFilter Filter): 조건에 맞는 목록 File[] 리턴

📚 Stream과 Reader, Writer

InputStream

  • 데이터를 읽을 때 사용
  • read()와 close() 메소드 꼭 기억
  • 하던 작업이 종료되면 close() 메소드로 꼭 닫아주어야 함
  • byte를 다룸

OutputStream

  • 데이터를 쓸 때 사용
  • flush(): 현재 버퍼에 있는 내용을 바로 저장시킴
  • close() 메소드를 사용해서 닫아주어야 함
  • byte를 다룸

Reader

  • char 기반의 문자열을 처리하기 위한 클래스
  • 모든 작업이 끝난 후 close() 호출
  • BufferedReader, InputStreamReader가 많이 사용

Writer

  • char 기반의 문자열을 처리하기 위한 클래스
  • OutputStream 메소드와 대부분 동일하지만 append() 존재
profile
배우고 활용하는 것을 즐기는 개발자, 한지연입니다!

0개의 댓글