5 분 소요

java.io.File

파일의 크기, 파일의 접근 권한, 파일의 삭제, 이름 변경 등의 작업을 할 수 있는 기능을 제공하여 준다. 디렉터리 또한 파일로 취급한다.

File 클래스 생성자

파일 인스턴스를 생성한다(실제 파일이 만들어지는 것은 아님).

생성자 설명
File(File parent, String child) parent 디렉터리에 child 파일에 대한 File 객체를 생성
File(String child) child 파일에 대한 File 객체를 생성
File(String parent, String child) parent 디렉터리에 child 파일에 대한 File 객체를 생성

File 클래스의 중요 메서드

메서드 설명
boolean canRead() 파일이 읽기 가능할 경우, true, 그렇지 않으면 false 반환
boolean canWrite() 파일이 쓰기 가능할 경우 true, 그렇지 않은 경우 false 반환
boolean createNewFile() 지정한 파일이 존재하지 않을 경우 새 파일을 생성
boolean delete() 파일을 삭제한다. 디렉터리일 경우 비어있을 때 삭제가 된다.
void deleteOnExit() JVM이 종료될 때 파일을 삭제한다.
boolean exits() 파일이 존재할 경우 true, 그렇지 않을 경우 false를 반환
String getAbsolutePath() 파일 절대 경로를 문자로 반환
String getCanonicalPath() 파일의 전체 경로를 문자열로 반환
String getName() 파일이나 디렉터리 이름을 반환
String getParent() 부모 경로의 경로명을 문자열로 반환
File getParentFile() 부모 디렉터리를 File의 형태로 반환
String getPath() 파일의 경로를 문자열 형태로 반환
boolean isDirectory() 디렉터리일 경우 true, 그렇지 않으면 false 반환

예제1

import java.io.File;
import java.io.IOException;

public class FileInfo {
    public static void main(String[] args) {
        if(args.length != 1) {
            System.out.println("사용법: java FileInfo 파일이름");
            System.exit(0); //return;
        }

        File f = new File(args[0]); //File 생성자 중 String 받는 생성자(java docs): 파일의 경로명을 넣어주면 된다
        if(f.exists()) {
            System.out.println("length : "+f.length());
            System.out.println("canRead : "+f.canRead());
            System.out.println("canWrite : "+f.canWrite());
            System.out.println("getAbsolutePath : "+f.getAbsolutePath());
            try {
                System.out.println("getCanonicalPath : "+f.getCanonicalPath());
            } catch(IOException e) {
                System.out.println(e);
            }
            System.out.println("getName : "+f.getName());
            System.out.println("getParent : "+f.getParent());
            System.out.printlnt("getPath : "+f.getPath());
        
        } else {
            System.out.println("파일이 존재하지 않습니다.");
        }
    }
}

예제2

import java.io.*;

public class FileDelete {
    public static void main(String[] args) {
        if(args.length != 1) {
            System.out.println("사용법: java FileDelete 파일이름");
            System.exit(0);
        }
        
        File f = new File(args[0]);
        if(f.exists()) {
            boolean deleteflag = f.delete();
            if(deleteflag)
                System.out.println("파일 삭제를 성공하였습니다.");
            else
                System.out.println("파일 삭제를 실패하였습니다.");
        } else {
            System.out.println("파일이 존재하지 않습니다.");
        }
    }
}

예제3: 피일리스트

import java.io.File;

public class FileList {
    public static void main(String[] args) {
        File file = new File("/tmp");

        if(file.isDirectory()) {
            File[] files = file.listFiles();
            for(int i = 0; i < files.length; i++) {
                System.out.println(files[i].getName());
            }
        } else {
            System.out.println(file.getNmae());
        }
    }
}

✨ IntelliJ의 메서드 추출 기능을 사용하여 main메서드에서 외재화 시켜보자!

import java.io.File;

public class FileList {
    public static void main(String[] args) {
        File file = new File("/tmp");

        printFiles(file);
    }

    private static void printFiles(File file) {
        if(file.isDirectory()) {
            File[] files = file.listFiles();
            for(int i = 0; i < files.length; i++) {
                printFiles(files[i]); // 재쉬 호출로 바꿨다.
            }
        } else {
            System.out.println(file.getNmae());
        }
    }
}

예제4: 임시파일

import java.io.*;

public class TempFile {
    public static void main(String[] args) {
        try {
            File f = File.createTempFile("tmp", ".dat");
            System.out.println("60초 동안 멈춰 있는다.") //60초 동안 멈춰 있는다.
            try {
                Thread.sleep(60000);
            } catch (InterruptedException e1) {
                System.out.prinln(e1);
            } 
            f.deleteOnExit(); // JVM이 종료될 때 임시 파일을 자동으로 삭제한다.
        } catch (IOException e) {
            System.out.println(e);
        }
    } 
}

ByteStream

Stream의 클래스 상속도

InputStrem, OutputStream

  • 추상클래스
  • byte 단위 입출력 클래스는 InputStream, OutputStream의 후손이다.

InputStream의 중요 메서드

메서드 설명
int available() throws IOException 현재 읽을 수 이쓴ㄴ 바이트 수를 반환
void close() throws IOException 입력 스트림을 닫는다.
int read() throws IOException 입력 스트림에서 한 바이트를 읽어서 int 값으로 반환한다. 더 이상 읽어들여야 할 내용이 없는 경우 -1 반환
int read(byte buf[]) throws IOException 입력 스트림에서 buf[] 크기만큼을 읽어 buf에 저장하고 읽은 바이트 수를 반환. 더이상 읽을 내용이 없을 경우 -1을 반환
int skip(long numBytes) throws IOException numBytes로 지정된 바이트를 무시하고, 무시된 바이트 수를 반환한다.

예제

import java.io.inputStream;

public class InputStreamEaxample1 {
    public static void main(String[] args) {
        InputStream in = null;
        try {
            int data = in.read(); // 바이트를 읽어들임, int로 반환
        } catch (IOException ioe) {
            System.out.println("io 오류 : "+ioe);
        } finally {
            try {
                in.close();
            } catch (Exception ex2) {
                System.out.println("io 오류2: " + ex2);
            } 
        }
    }
}
  • 1 바이트 = 8 비트: 00000000 ~ 11111111

read() 메서드가 읽어들일 수 있는 정보: 00000000 ~ 11111111

  • 1 바이트씩 읽어들인다: 파일 크기를 모름, 언제까지 읽어야 하나?

→ 더이상 읽어들일 것이 없을 때까지: EOF

  • 바이트 단위만으로는 EOF를 표현할 수 없음. int 단위로 읽자: 맨 마지막 바이트만 사용

→ 0000000 00000000 00000000 00000000 ~ 0000000 00000000 00000000 11111111

  • EOF는 -1로 한다.
숫자 바이트 표현
1 00000000 00000000 00000000 00000001
1의 보수 11111111 11111111 11111111 11111110
2의 보수 11111111 11111111 11111111 11111111

1의 보수는 반전, 2의 보수는 1의 보수에 1 더한 값

2의 보수는 원래 수와 더하면 0이 되어버리므로 -1을 표현한 것으로 본다.

생각해보자

  1. txt 파일로부터 한 줄 씩 입력ㅂ다아 화면에 출력한다.
  2. 키보드로부터 한 줄 씩 입력받아 파일에 출력한다. 파일명은 아규먼트로.
  3. txt 파일로부터 한 줄 씩 입력받아 다른 파일에 한 줄 씩 출력한다.

태그:

카테고리:

업데이트:

댓글남기기