개발이야기/Java

[Java] File 내용 읽고 파일 정보 출력하기 (File 클래스 사용법, 예제)

후린개발자 2023. 12. 14.
반응형

아래 소스코드는 주어진 폴더 경로에서 .xlsx 확장자를 가진 엑셀 파일을 찾아 읽고, 각 셀의 내용을 출력하며 해당 파일에 대한 기본 정보를 출력하는 소스코드입니다.

 

 

소스코드 설명

1.폴더 경로 설정

String folderPath = "D:\\test"; // 폴더 경로

 

-D:\\test 경로에 있는 엑셀 파일들을 처리합니다.

 

 

2.폴더 확인 및 파일 목록 가져오기

File folder = new File(folderPath);

if (!folder.exists() || !folder.isDirectory()) {
    System.err.println("폴더가 존재하지 않습니다.");
    return;
}

File[] files = folder.listFiles();

 

-지정된 폴더가 존재하는지 확인하고, 폴더 내 파일 목록을 가져옵니다.

 

 

3.파일 처리 및 정보 출력

if (files != null) {
    for (File file : files) {
        if (file.isFile() && file.getName().endsWith(".xlsx")) {
            // 엑셀 파일인 경우에만 처리
            readExcelFile(file);

            // 파일 정보 출력
            printFileInfo(file);
        }
    }
} else {
    System.err.println("폴더 내 파일을 읽어올 수 없습니다.");
}

 

-.xlsx 확장자를 가진 엑셀 파일을 찾아서 readExcelFile 메서드로 읽고, printFileInfo 메서드로 파일의 기본 정보를 출력합니다.

 

 

4.Excel 파일 읽기

FileInputStream fileInputStream = new FileInputStream(file);
Workbook workbook = new XSSFWorkbook(fileInputStream);

 

-FileInputStream을 이용하여 엑셀 파일을 읽고, XSSFWorkbook으로 엑셀 워크북을 생성합니다.

 

 

5.셀 내용 출력

for (Row row : sheet) {
    for (Cell cell : row) {
        // ... (각 셀의 내용에 따라 출력)
    }
    System.out.println(); // 다음 행으로 이동
}

 

-엑셀 시트의 각 행 및 셀을 반복하며, 셀의 내용에 따라 다른 처리를 수행하고 출력합니다.

 

 

6.파일 및 워크북 닫기

fileInputStream.close();
workbook.close();

 

-파일 스트림과 워크북을 닫아서 자원을 해제합니다.

 

 

7.파일 정보 출력

 

file.exists():

-파일이나 디렉토리가 실제로 존재하는지 여부를 확인합니다.

-true면 파일이 존재하고, false면 파일이나 디렉토리가 존재하지 않습니다.

file.getName():

-파일이나 디렉토리의 이름을 반환합니다.

file.getAbsolutePath():

-파일이나 디렉토리의 절대 경로를 반환합니다.

file.length():

-파일의 크기를 바이트 단위로 반환합니다.

 

 

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class TEST {
    public static void main(String[] args) {
        String folderPath = "D:\\test"; // 폴더 경로

        File folder = new File(folderPath);

        // 폴더가 존재하는지 확인
        if (!folder.exists() || !folder.isDirectory()) {
            System.err.println("폴더가 존재하지 않습니다.");
            return;
        }

        // 폴더 내의 파일 목록 가져오기
        File[] files = folder.listFiles();

        if (files != null) {
            for (File file : files) {
                if (file.isFile() && file.getName().endsWith(".xlsx")) {
                    // 엑셀 파일인 경우에만 처리
                    readExcelFile(file);
                    
                    // 파일 정보 출력
                    printFileInfo(file);
                }
            }
        } else {
            System.err.println("폴더 내 파일을 읽어올 수 없습니다.");
        }
    }
    private static void readExcelFile(File file) {
        try {
            FileInputStream fileInputStream = new FileInputStream(file);

            // 엑셀 워크북 생성
            Workbook workbook = new XSSFWorkbook(fileInputStream);

            // 첫 번째 시트 선택
            Sheet sheet = workbook.getSheetAt(0);

            // 각 행을 반복하며 셀의 내용 출력
            for (Row row : sheet) {
                for (Cell cell : row) {
                    switch (cell.getCellType()) {
                        case STRING:
                            System.out.print(cell.getStringCellValue() + "\t");
                            break;
                        case NUMERIC:
                            if (DateUtil.isCellDateFormatted(cell)) {
                                // Date 형식인 경우
                                Date date = cell.getDateCellValue();
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                System.out.print(sdf.format(date) + "\t");
                            } else {
                                // 숫자 형식인 경우
                                System.out.print(cell.getNumericCellValue() + "\t");
                            }
                            break;
                        case BOOLEAN:
                            System.out.print(cell.getBooleanCellValue() + "\t");
                            break;
                        case BLANK:
                            System.out.print("[BLANK]\t");
                            break;
                        default:
                            System.out.print("[UNKNOWN]\t");
                    }
                }
                System.out.println(); // 다음 행으로 이동
            }

            // 파일 스트림 닫기
            fileInputStream.close();
            // 워크북 닫기
            workbook.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static void printFileInfo(File file) {
        if (file.exists()) {
            System.out.println("파일이 존재합니다.");
            System.out.println("파일 이름: " + file.getName());
            System.out.println("파일 경로: " + file.getAbsolutePath());
            System.out.println("파일 크기: " + file.length() + " bytes");
        } else {
            System.out.println("파일이 존재하지 않습니다.");
        }
    }
}

 

 


 

콘솔 출력 결과

 

엑셀 파일내용

반응형

댓글

💲 추천 글