티스토리 뷰

1. 파일 관련 입출력

1-1. 파일 클래스(File Class)란?

💡 파일 시스템의 파일을 다루기 위한 클래스.
파일의 크기나 속성, 이름 등의 정보를 확인할 수 있고 파일 생성 및 삭제 기능 등을 제공한다.
File file = new File("file path");
File file = new File("C:/data/childDir/grandChildDir/fileTest.txt");
// 그냥 인식을 시키는 것이다.

 

package com.ohgiraffers.section01.file;

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

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

        /* 수업목표. File 클래스의 사용 용법을 이해할 수 있다. */
        File file = new File("src/main/java/com/ohgiraffers/section01/file/test.txt"); // '\\'와 '/' 는 같다. 근데 안된다?????????
        // 파일이 실제 생긴 것이 아니라 이 경로로 만들거야 알려줌

        try {
            boolean isSuccess = file.createNewFile();
            System.out.println("파일 생성 여부: " + isSuccess);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        /* 설명. 몇 가지 File에서 제공하는 메소드 확인 */
        System.out.println("파일의 크기: " + file.length() + "byte");
        System.out.println("파일의 경로: " + file.getPath());
        System.out.println("현재 파일의 상위 경로: " + file.getParent());
        System.out.println("파일의 절대 경로: " + file.getAbsolutePath());

        boolean isDeleted = file.delete();
        System.out.println("파일 삭제 여부: " + isDeleted);

    }
}

// 실행 결과
파일 생성 여부: true

파일의 크기: 0byte
파일의 경로: src/main/java/com/ohgiraffers/section01/file/test.txt
현재 파일의 상위 경로: src/main/java/com/ohgiraffers/section01/file
파일의 절대 경로: /Users/kimjeongmo/Desktop/한화시스템 Beyond SW/lecture/01_java/chap11-io-lecture-source/src/main/java/com/ohgiraffers/section01/file/test.txt

파일 삭제 여부: true

1-2. 파일 입출력 관련 기반 스트림의 종류

1-2-1. 바이트 단위(영어, 숫자, 특수기호 사용 시)

  • InputStream

package com.ohgiraffers.section02.stream;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

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

        /* 수업목표. 입출력 스트림에 대해 이해하고 파일을 대상으로 하는 FileInputStream 을 사용할 수 있다. */
        FileInputStream fis = null;     // try 블럭 밖에서 선언해줘야 한다.
        try {
            fis = new FileInputStream("src/main/java/com/ohgiraffers/section02/stream/testInputStream.txt");
//            System.out.println((char)fis.read());
//            System.out.println((char)fis.read());
//            System.out.println((char)fis.read());
//            System.out.println((char)fis.read());
//            System.out.println((char)fis.read());

            int input = 0;

            /* 설명. 파일의 끝(EOF)을 만날 때까지 1byte 씩 읽어들일 수 있도록 조건식 작성 */
            while ((input = fis.read()) != -1) {    // 1byte씩!! input 변수 사용안하면 2byte씩?????????????????
                System.out.println((char)input);
            }

        } catch (FileNotFoundException e) {
            System.out.println("파일 경로 확인해!!!");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if(fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}

// 실행 결과
H
e
l
l
o
 
W
o
r
l
d
!
1
2
3
?
// testinputStream.txt

Hello World!123?
  • OutputStream

package com.ohgiraffers.section02.stream;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

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

        /* 수업목표. FileOutputStream 에 대해 이해하고 활용할 수 있다. */
        FileOutputStream fout = null;
        try {

            /* 설명. 해당 경로에 파일이 없으면 만들어 줌(출력 스트림만 만들어도) */
            /* 설명. OutputStream 생성자 중에 append 개념을 추가하는 인자를 true 로 넘겨주면 데이터 이어붙이기가 가능하다. */
            fout = new FileOutputStream("src/main/java/com/ohgiraffers/section02/stream/testOutputStream.txt", true);

//            fout.write('a');
//            fout.write(66);

            byte[] bArr = new byte[]{'a', 'p', 'p', 'l', 'e'};
//            for (byte b : bArr) {
//                fout.write(b);
//            }

            fout.write(bArr, 1, 3);         // 인덱스 1번부터 3개 출력

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (fout != null) fout.close();     // if문 같은 블럭에서 실행구문이 한 줄이면 중괄호 생략 가능
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
// testOutputStream.txt

ppl

1-2-2. 문자 단위(한글까지 사용 시)

  • Reader

package com.ohgiraffers.section02.stream;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

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

        /* 수업목표. FileReader 를 이해하고 활용할 수 있다. */
        /* 필기.
        *   FileReader 는 인코딩 방식에 맞게 한 글자씩 입력 받을 수 있는 스트림이다.
        *   (숫자/특수기호/영어 - 1byte, 한글/그 외 언어 - 3byte (UTF-8)
        * */
        FileReader fr = null;
        try {
            fr = new FileReader("src/main/java/com/ohgiraffers/section02/stream/testReader.txt");

            int readChar = 0;
            while((readChar = fr.read()) != -1) {
                System.out.println((char)readChar);     // 나중에 이해!!!!!!!!!???????????
            }

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if(fr != null) fr.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

// 실행 결과
세
종
대
왕
 
만
만
세
!
// testReader.txt

세종대왕 만만세!
  • Writer

package com.ohgiraffers.section02.stream;

import java.io.FileWriter;
import java.io.IOException;

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

        /* 수업목표. FileWriter 에 대해 이해하고 활용할 수 있다. */
        FileWriter fw = null;
        try {
            fw = new FileWriter("src/main/java/com/ohgiraffers/section02/stream/testWriter.txt");

            fw.write('한');
            fw.write("글");

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if(fw != null) fw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
// testWriter.txt

한글

 

package com.ohgiraffers.section03.filterstream;

import java.io.*;

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

        /* 수업목표. BufferedWriter 와 BufferedReader 에 대해 이해하고 사용할 수 있다. */
        /* 설명.
        *   내부적으로 버퍼(buffer)를 활용해서 입출력 성능을 향상 시킨다.
        *   추가적인 메소드가 제공된다.
        *  */

        /* 설명. BufferWriter 를 활용한 한 줄씩 출력하기 */
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(
                    new FileWriter(
                    "src/main/java/com/ohgiraffers/section03/filterstream/testBuffered.txt", true));
            bw.write("제목: 세종대왕님\n");
            bw.write("드디어 세종대왕님이 만족하시겠네!\n");
            bw.write("대한민국 최고");

            /* 설명.
            *   버퍼를 이용해서 출력을 하는 경우 버퍼 공간이 가득차지 않으면 내보내기(출력)가 안되는 경우가 있다.
            *   이럴 경우 버퍼에 담긴 내용을 강제로 내보내기 위해서는 flush()메소드를 활용해야 한다.
            *   (write 를 했는데 파일에 값이 안 적혀 있으면 flush()할 것)
            *  */
            bw.flush();

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {

                /* 설명. 보조스트림을 닫으면 그 이전에(내부에) 만든 스트림들은 자동으로 close() 된다. */
                if(bw != null) bw.close();          // BufferedWriter 스트림을 닫으면 내부적으로 flush()가 동작한다.
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }


        /* 설명. BufferedReader 를 활용한 한 줄(개행 문자 전까지) 싹 읽어오기 */
        BufferedReader br = null;
        try {
            br = new BufferedReader(
                    new FileReader(
                            "src/main/java/com/ohgiraffers/section03/filterstream/testBuffered.txt"));

            String rstr = "";
            while((rstr = br.readLine()) != null) {
                System.out.println(rstr);
            }

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if(br != null) br.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

// 실행 결과
제목: 세종대왕님
드디어 세종대왕님이 만족하시겠네!
대한민국 최고
// testBuffered.txt

제목: 세종대왕님
드디어 세종대왕님이 만족하시겠네!
대한민국 최고

1-3. 파일 입출력 관련 보조 스트림의 종류

💡 스트림의 기능을 향상시키거나 새로운 기능을 추가하기 위해 사용.
보조 스트림만으로는 데이터를 주고 받는 대상에 대한 처리를 하는 것이 아니므로 입출력 처리가 불가능하고 기반 스트림에 추가로 적용되어야 한다.

1-3-1. 입출력 성능 향상

  • BufferedInputStream / BufferedOutputStream
    • 입출력 속도 향상 및 한 줄씩 출력 및 입력 관련 메소드 제공 보조 스트림
    • 코드는 `1-3-4. 객체 자료형 데이터 입출력` 코드 같이 보자!

1-3-2. 형변환 보조스트림

  • InputStreamReader / OutputStreamWriter
    • 인코딩 방식을 고려한 한글 깨짐 방지를 위해 고려할 수 있는 보조 스트림
package com.ohgiraffers.section03.filterstream;

import java.io.*;

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

        /* 수업목표. 표준입출력(콘솔을 통한 입출력)을 이해하고 활용할 수 있다. */
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));   // System.in -> 기반스트림

        System.out.print("문자열 입력: ");
        try {
            String input = br.readLine();

            System.out.println("input = " + input);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if(br != null) br.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        BufferedWriter bw = null;
        OutputStreamWriter osw = null;
        osw = new OutputStreamWriter(System.out);
        bw = new BufferedWriter(osw);

        try {
            bw.write("println이 좋은거구만!~");   // 콘솔로 내보냄
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(bw != null) bw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}

실행 결과

1-3-3. 기본 자료형 데이터 입출력

  • DataInputStream / DataOutputStream
    • 기본자료형 및 문자열 관련 타입에 따른 메소드를 제공하는 보조 스트림
package com.ohgiraffers.section03.filterstream;

import java.io.*;

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

        /* 수업목표. 데이터 타입 입출력 보조 스트림을 이해하고 활용할 수 있다. */   // 거의 안씀.
        DataOutputStream dos = null;
        try {
            dos = new DataOutputStream(
                    new FileOutputStream(
                            "src/main/java/com/ohgiraffers/section03/filterstream/testData.txt"));

            dos.writeUTF("홍길동");
            dos.writeInt(20);
            dos.writeChar('A');

            dos.writeUTF("유관순");
            dos.writeInt(16);
            dos.writeChar('B');

            dos.writeUTF("강감찬");
            dos.writeInt(38);
            dos.writeChar('O');

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if(dos != null) dos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        DataInputStream dis = null;
        try {
            dis = new DataInputStream(
                    new FileInputStream(
                            "src/main/java/com/ohgiraffers/section03/filterstream/testData.txt"));

            while (true) {
                System.out.println(dis.readUTF());      // 순서!
                System.out.println(dis.readInt());
                System.out.println(dis.readChar());
            }

        } catch (EOFException e) {

            /* 설명. data 단위 입출력은 EOFException 을 활용하여 파일의 끝까지 입력 받았다는 것을 처리할 수 있다. */ // -1을 반환받지 못한다.
            System.out.println("파일을 다 읽어냄");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if(dis != null) dis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

1-3-4. 객체 자료형 데이터 입출력

  • ObjectInputStream / ObjectOutputStream
    • 객체 단위 입출력을 위한 보조 스트림
package com.ohgiraffers.section03.filterstream;

import com.ohgiraffers.section03.filterstream.dto.MemberDTO;

import java.io.*;

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

        MemberDTO[] memArr = new MemberDTO[100];
        memArr[0] = new MemberDTO("user01", "pass01", "홍길동"
                        , "hong123@gmail.com", 25, '남');
        memArr[1] = new MemberDTO("user02", "pass02", "유관순"
                        , "korea31@gmail.com", 16, '여');
        memArr[2] = new MemberDTO("user03", "pass03", "이순신"
                        , "leesoonsin@gmail.com", 38, '남');

        File ObjFile = new File("src/main/java/com/ohgiraffers/section03/filterstream/testObject.txt");

        ObjectOutputStream objOut = null;
        try {
            if (!ObjFile.exists()) {
                objOut = new ObjectOutputStream(
                        new BufferedOutputStream(
                                new FileOutputStream(
                                        "src/main/java/com/ohgiraffers/section03/filterstream/testObject.txt")
                        )
                );
            } else {
                objOut = new MyOutput(
                        new BufferedOutputStream(
                                new FileOutputStream(
                                        "src/main/java/com/ohgiraffers/section03/filterstream/testObject.txt", true)
                        )
                );
            }

//            for (int i = 0; i < 3; i++) {
//                objOut.writeObject(memArr[i]);
//            }

            for (int i = 0; i < memArr.length; i++) {
                if (memArr[i] == null) break;
                objOut.writeObject(memArr[i]);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (objOut != null) objOut.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        MemberDTO[] newMemArr = new MemberDTO[memArr.length];

        ObjectInputStream objIn = null;
        try {
            objIn = new ObjectInputStream(
                    new BufferedInputStream(
                            new FileInputStream(
                                    "src/main/java/com/ohgiraffers/section03/filterstream/testObject.txt")
                    )
            );

            int i = 0;
            while (true) {
                newMemArr[i] = (MemberDTO) objIn.readObject();
                i++;
            }
        } catch (EOFException e) {
            System.out.println("객체 단위 파일 입력 완료!");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (objIn != null) objIn.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        for (MemberDTO m : newMemArr) {
            if (m == null) break;
            System.out.println(m);
        }
    }
}

// 실행 결과
객체 단위 파일 입력 완료!
MemberDTO{id='user01', pwd='pass01', name='홍길동', email='hong123@gmail.com', age=25, gender=남}
MemberDTO{id='user02', pwd='pass02', name='유관순', email='korea31@gmail.com', age=16, gender=여}
MemberDTO{id='user03', pwd='pass03', name='이순신', email='leesoonsin@gmail.com', age=38, gender=남}
package com.ohgiraffers.section03.filterstream.dto;

import java.io.Serializable;

public class MemberDTO implements Serializable {	// 직렬화!!

    private String id;
    private String pwd;
    private String name;
    private String email;
    private int age;
    private char gender;

    public MemberDTO() {
    }

    public MemberDTO(String id, String pwd, String name, String email, int age, char gender) {
        this.id = id;
        this.pwd = pwd;
        this.name = name;
        this.email = email;
        this.age = age;
        this.gender = gender;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public char getGender() {
        return gender;
    }

    public void setGender(char gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "MemberDTO{" +
                "id='" + id + '\'' +
                ", pwd='" + pwd + '\'' +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                ", gender=" + gender +
                '}';
    }
}
package com.ohgiraffers.section03.filterstream;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

/* 설명. 우리만의 헤더 추가가 안되는 ObjectOutputStream 만들어 보기 */
public class MyOutput extends ObjectOutputStream {
    public MyOutput(OutputStream out) throws IOException {
        super(out);
    }

    @Override
    protected void writeStreamHeader() throws IOException {
        // 헤더 기능이 없다.????????????????

        /* 설명. 객체 출력 시 헤더의 개념이 추가되지 않도록 기능 삭제 */
    }
}

 

 

 

'한화시스템 > 백엔드' 카테고리의 다른 글

[BE] JAVA_컬렉션(Collection)_개요  (1) 2024.07.23
[BE] JAVA_제네릭스(Generics)  (0) 2024.07.23
[BE] JAVA_입출력_개요  (1) 2024.07.22
[BE] JAVA_예외처리  (0) 2024.07.20
[BE] JAVA_API_Time 패키지  (0) 2024.07.20
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함