Java

[Java] 파일 클래스

에띠 2022. 4. 18. 13:24
728x90

File 

File 클래스
- 파일(디렉토리) 자체를 다루는 클래스
- 입출력 관련 작업

    File 참조변수 = new File(파일 주소 또는 파일이름);

File file1 = new File("D:\\study\\new\\java\\day10\\input1.txt");

 

File 클래스의 메소드

- exists() : 파일이 실제 존재하는지 여부
- isDirectory() : 해당 경로가 디렉토리인지 여부
- isFile() : 해당 경로가 파일인지 여부
- length() : 파일 데이터 길이(byte)를 반환, 한글 3byte, 영어/특수문자/띄어쓰기 1byte

- mkdir() : 폴더를 생성
- createNewFile() : 파일을 생성
- renameTo() : 매개변수로 전달된 파일과 같은 디렉토리로 이름 변경 및 이동 수행

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

public class File1 {
    public static void main(String[] args) {
        try {
            File file1 = new File("D:\\study\\new\\java\\day10\\input1.txt");
            System.out.println(file1.exists()); // exists() : 파일 존재 여부 반환
            System.out.println(file1.isDirectory()); // isDirectory() : 현재 file1이 폴더인지 여부
            System.out.println(file1.isFile()); // isFile() : 현재 file1이 파일인지 여부
            System.out.println(file1.length()); // length() : file1의 텍스트 byte 수
            System.out.println();

            File dir = new File("D:\\study\\new\\java\\day10\\new\\subDir");
            dir.mkdir(); // mkdir() : 폴더 생성.

            File file2 = new File(dir, "input2.txt"); // dir내 input2.txt 파일 생성
            file2.createNewFile(); // createNewFile() : 파일 생성.

            File file3 = new File("input3.txt");
            file2.renameTo(file3); // renameTo() : 파일이름 변경후 root에 저장

            System.out.println(file3.getPath()); // 상대 경로(실행되는 파일 기준)
            System.out.println(file3.getAbsolutePath()); // 절대 경로
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

스트림(stream)
- 자바는 파일이나 콘솔의 입출력을 직접 다루지 않고 스트림이라는 흐름을 통해 다룸
- 운영체제에 의해 생성되는 가상의 연결고리를 의미하고 중간 매개자 역할을 함

    Java 프로그램 ----------> OS(운영체제) -----------> 모니터, 프린터, 디스크, 네트워크
                           <----------                         <-----------
                                          데이터의 흐름...


FileInputStream Vs FileOutputStream

FileInputStream 클래스
- java.io의 가장 기본이 되는 입력 클래스 // io : input, output
- 입력 스트림(통로)을 생성해줌
- 버퍼를 사용하지 않기 때문에 느릴 수 있음 // 파일을 전송 시 일부씩 쪼개서 넘김. 버퍼 : 넘어오는 파일을 안정화될 때 까지 모아 뒀다가 화면에 뿌려줌(속도 느림)
- 속도 문제를 해결하기 위해 버퍼를 사용하는 다른 클래스와 같이 사용하는 것이 일반적

- read() : 스트림을 통해 byte 단위로 데이터를 읽어옴

 

FileOutputStream 클래스
- java.io의 가장 기본이 되는 출력 클래스
- 출력 스트림(통로)을 생성해줌
- 버퍼를 사용하지 않기 때문에 느릴 수 있음
- 속도 문제를 해결하기 위해 버퍼를 사용하는 다른 클래스와 같이 사용하는 것이 일반적

- write() : 스트림을 통해 byte 단위로 데이터를 씀

 

import java.io.FileInputStream;

public class File2 {
    public static void main(String[] args) {
        byte[] arr1 = new byte[20];
        byte[] arr2 = new byte[20];

        try {
            FileInputStream fis = new FileInputStream("input4.txt");
            System.out.println((char) fis.read()); // read() : 정수형으로 반환되기 때문에 (char)로 형변환 한글자 반환 "H"
            fis.read(arr1, 0, 5); // 읽어온 문자 이후로 0번째 문자부터 5byte를 arr1에 저장 "ello "
            for (byte b : arr1) {
                System.out.print((char) b + " ");
            }

            fis.read(arr2); // file을 읽어와서 arr2에 저장.
            System.out.println();
            for (byte b : arr2) {
                System.out.print((char) b + " "); // arr1에 저장된 문자 이후로 가져옴.
            }
            fis.close(); // 파일 사용 후 close()를 무조건 해줘야 함(스트림 연결 끊음).
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

FileReader

FileReader 클래스
- FileInputStream과 유사
- 문자 스트림으로서 문자 단위의 바이트 변환 기능을 가지고 있음
- 바이트 단위가 아닌 문자 단위로 입출력을 실행

import java.io.FileReader;

public class File4 {
    public static void main(String[] args) {
        char[] arr = new char[40];
        try {
            FileReader fr = new FileReader("input1.txt");
            System.out.println((char)fr.read()); // char의 배열 형태로 데이터를 읽어옴
            fr.read(arr); // 파일을 읽어와서 arr에 저장
            for (char c : arr) {
                System.out.print(c);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

FileWriter 

FileWriter 클래스
- FileOutputStream과 유사
- 문자 스트림으로서 문자 단위의 바이트 변환 기능을 가지고 있음
- 바이트 단위가 아닌 문자 단위로 입출력을 실행

import java.io.FileWriter;

public class File5 {
    public static void main(String[] args) {
        String str = "Hello Java!";

        try {
            FileWriter fw = new FileWriter("output2.txt");
            fw.write(str.charAt(0)); // str의 0번째를 fw에 작성
            fw.write("\t"); // tab
            fw.write(str);
            fw.write("\n"); // 줄바꿈
            fw.write("안녕하세요");

            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

PrintWriter 

PrintWriter 클래스
- 문자열을 출력하는 스트림 Writer 속성을 가진 클래스
- OutputStream의 자식 클래스이며, byte 단위 출력 클래스인 PrintStream의 Print 메소드를 모두 구현하여 사용할 수 있음

import java.io.FileOutputStream;
import java.io.PrintWriter;

public class File7 {
    public static void main(String[] args) {
        String file1 = "output3.txt";
        String[] arr = {"김사과", "오렌지", "반하나", "이메론"};

        try {
//            FileOutputStream fos = new FileOutputStream(file1);
//            PrintWriter pw = new PrintWriter(fos);
            PrintWriter pw = new PrintWriter(new FileOutputStream(file1));
            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i] + " ");
                pw.println(arr[i]); // line 별로 작성
            }
            pw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

 

 

728x90