JAVA

2021-08-13 오전 (File)

BSYeop 2021. 8. 13. 12:11

File

  • 자바에서 파일이나 디렉터리를 다룰 수 있도록 제공해주는 클래스
  • File 클래스에서 제공되는 주요 생성자,메소드는 p470 ~ p471 참고

ex) FileExample

  • 이 예제를 실행하기 위해 C: 아래에 data 디렉터리를 생성해야한다
package kr.ac.daegu.bsy;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Scanner;

public class FileTest1 {

    // 확장자가 ".jpg"로 끝나는 파일 이름을 필터링해주는 클래스
    public static class ImageNameFilter implements FilenameFilter{
        @Override
        public boolean accept(File dir, String name){
            return name.endsWith(".jpg");
        }
    }
    /*
     * File 클래스 메소드 사용하기
     */

    public static void main(String[] args) {
        System.out.println("FileExample");
        // p.471 ~ p.473
        System.out.println("c: 드라이브의 전체 파일 출력");
        File file = new File("C:\\");  // C: 드라이브 경로를 이용해서 파일 객체를 생성(자바에서 파일의 경로를 지정할 때는 "\\"나 "/" 사용)  // pathname에 위치한 파일/디렉토리의 정보(디렉터리인지? 파일이름들...)을 모두 가져옴

        String[] files = file.list();       //C:드라이브 안에 존재하는 모든 디렉터리와 파일 이름을 String[] 타입으로 얻어 오는 부분

        // 1. 부모 경로와 파일 이름을 이용해서 자식 파일 객체들을 생성
        // 2. 생성한 파일 객체가 디렉터리일 경우 정보를 출력
        // 3. 생성한 파일 객체가 파일일 경우 정보를 출력
        for (String fileName : files){
            File subFile = new File(file,fileName);  // pathname(file)에 속한 파일 이름 (fileName)를 생성자 파라미터로 제공하여 한개의 파일 객체를 메모리에 적재한다
            if (subFile.isDirectory()){
                System.out.println("디렉터리 이름 : " + fileName);
            }
            else {
                System.out.println("파일 이름 : " + fileName + ", 파일 크기 : " + subFile.length()+ "byte");
            }
        }

        System.out.println("c : 드라이브의 이미지 파일만 출력");
        String[] imageFiles = file.list(new ImageNameFilter()); // 확장자가 ".jpg"로 끝나는 파일 이름들만 String 타입으로 가져옴

        // 파일의 정보 출력
        // getAsoultePath() : 절대 경로 C://sadasd/asdasfas/asddasd/sadasdsa/asdadssad.jpg
        // 상대경로 : 경로 자체를 호출하는 파일의 위치를 기준으로 쓰는 경로 (.././)
        for (String fileName : imageFiles){
            File subFile = new File(file,fileName);
            System.out.println("파일 이름 : " + fileName + ", 파일 크기 : " + subFile.length() + "byte" + ", 파일 경로 : " + subFile.getAbsolutePath());
        }

        File makeFile = new File("c:\\data\\testFile.txt"); // 생성할 파일 객체를 추성적으로 만드는 부분(추상적인 객체가 메모리상에 생성)

        // 물리적으로 파일을 생성하는 부분
        try {
            makeFile.createNewFile();  // java 언어에서는 일부 객체의 메소드에 한해 강제적인 예외처리를 요구한다.(파일접근, DB관련, ...) - java 시스템 바깥의 어떤 시스템에 접근해서 뭔가를 하고 싶을때
        }
        catch (IOException e){ // 파일처리의 경우 담당하는 예외
            e.printStackTrace();
        }

        //파일이 정상적으로 생성되었으면 메세지를 출력
        if (makeFile.exists()){
            System.out.println("makeFile이 생성됨");
        }
        File renameFile = new File ("c:\\data\\testFile2.txt"); // 추상적인 파일 객체를 하나 더 생성
        makeFile.renameTo(renameFile);                                   // 파일의 이름을 파라미터로 지정된 파일의 이름을 변경하는 부분
        //파일 이름이 정상적으로 변경되었으면 메세지를 출력
        if (renameFile.exists()){
            System.out.println("makeFile의 이름이 변경됨");
        }
        //해당 파일을 제거하는 작업 후 파일이 제대로 제거되었으면 메세지를 출력
        if (renameFile.delete()){
            System.out.println("renameFile이 제거됨");
        }
    }
}

ex) FileExample2

  • 이 예제를 실행하기 위해 FileExample 예제에서 만든 data 디렉터리에 test.txt라는 파일을 만들어야한다
package kr.ac.daegu.bsy;

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

public class InputStreamTest {

    /*
     * InputStream 테스트
     */
    // 예외처리 사용자나 개발자에게 문제가 일어났을 시 빠르게 파악하기위해 사용하는 용도

    public static void main(String[] args) {

        // p.478 ~ p.479
        // 예제의 의도? 파일의 컨텐츠를 어떻게 읽어 들여 출력 할까?
        System.out.println("FileExample2");
        FileInputStream fIn = null;

        try{
            // C, C++ : 메모리에 객체를 적재 명령을 하면, 런타임에서 해당 객체를 다 쓰고 난 뒤에 "해제"하는 코드를 넣어줘야 한다.
            // GARBEGE COLLECTOR (쓰레기 수집기) : New Instance(); 객체를 메모리에 적재하고 GC가 '알아서' 메모리에 해제한다.
            fIn = new FileInputStream("C:\\data\\test.txt"); // 메모리(RAM)의 자원을 고정해서 점유한다
        }
        catch (IOException io){
            io.printStackTrace();
        }
        int var_read = -1;

        try {
            while ((var_read = fIn.read()) != -1){
                System.out.print((char)var_read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally { // try 블록에서 exception이 발생이 되던 안되던 실행되는 블록
            try {
                fIn.close(); // 메모리에(RAM) 자원 반납
            }
            catch (IOException io){
                io.printStackTrace();
            }
        }
    }
}

 

ex) FileExample3

  • 이 예제를 실행하기 위해 FileExample3 폴더안에 test1.txt, test2.txt, test3.txt 파일을 생성해야한다
package kr.ac.daegu.bsy;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
import java.util.Enumeration;
import java.util.Vector;

public class SequenceInputStreamTest {

    public static void main(String[] args) {
        System.out.println("FileExample3");
        // p.481 ~ p.483

        FileInputStream fIn1 = null;
        FileInputStream fIn2 = null;
        FileInputStream fIn3 = null;
        SequenceInputStream si1 = null;
        SequenceInputStream si2 = null;

        try{
            fIn1 = new FileInputStream("test1.txt");
            fIn2 = new FileInputStream("test2.txt");
            fIn3 = new FileInputStream("test3.txt");

            Vector v = new Vector();
            v.add(fIn1);
            v.add(fIn2);
            v.add(fIn3);

            Enumeration fIns = v.elements();
            si1 = new SequenceInputStream(fIns);

            int var_readbyte = -1;
            while ((var_readbyte = si1.read()) != -1){
                System.out.print((char) var_readbyte);
            }
            System.out.println();

            fIn1 = new FileInputStream("test1.txt");
            fIn2 = new FileInputStream("test2.txt");
            si2 = new SequenceInputStream(fIn1,fIn2);
            var_readbyte = -1;
            while ((var_readbyte = si2.read()) != -1){
                System.out.print((char) var_readbyte);
            }
        }
        catch (IOException io){
            io.printStackTrace();
        }
        finally {
            try{
                si1.close();
                si2.close();
            }
            catch (IOException io){
                io.printStackTrace();
            }
        }
    }
}

ex) FileExample4

package kr.ac.daegu.bsy;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class FileOutputStreamTest {

    public static void main(String[] args) {
        System.out.println("FileExample");
        // p.485 ~ p.486
        // java 코드에서 생성한 문자열 데이터를 FileOutputStream 이용하여 fileOutput.txt에 쓰기.
        FileOutputStream fo = null;
        String msg = "FileOutputStream Test 안녕하세요";
        byte[] byteArray = msg.getBytes(); // msg.getBytes(StandardCharsets.UTF_8)안전하게 UTF=8인코딩 지정하여 다국어(한글) 지정 할 수 있도록

        try{
            // 상대경로를 지정할때 어떻게 테스트 해가면서 쓸지? : ./ 찍어서 실제 동작이 어떻게 되는지 확인하고 작성.
            // apppend의 뜻. : 기존 컨텐츠에 ++.
            fo = new FileOutputStream("fileout.txt",true);
            fo.write(byteArray);
        }
        catch (IOException io){
            io.printStackTrace();
        }
        finally {
            {
                try {
                    fo.close();
                }
                catch (IOException io){
                    io.printStackTrace();
                }
            }

            // 번외 : StringBuilder (append에 대한 추가 설명)
            StringBuilder sb = new StringBuilder();
            sb.append("hihi");
            sb.append("방가방가");
            System.out.println(sb);
            String str = "hihi";
            str = str + "방가방가";
            System.out.println(str);
        }
    }
}