파일 사이즈 구하기

파일 사이즈를 얻는 방법으로는 2가지 클래스가 있습니다.

java.io.File, java.nio.file

java.io.File의 length() 함수 이용하기

java.io.File file = new java.io.File("example.txt");
long fileSize = file.length();
System.out.println("File Size: " + fileSize + " bytes");

java.nio.file.Files의 size() 함수 이용하기

java.nio.file.Path path = java.nio.file.Paths.get("example.txt");
long fileSize = java.nio.file.Files.size(path);
System.out.println("File Size: " + fileSize + " bytes");

얻은 파일 사이즈는 모두 Byte 단위입니다.

KB, MB, GB 형식으로 변환하려면 아래 함수를 이용하세여.

public static String formatFileSize(long sizeInBytes) {
    String[] units = {"B", "KB", "MB", "GB", "TB"};
    int unitIndex = 0;
    while (sizeInBytes > 1024 && unitIndex < units.length - 1) {
        sizeInBytes /= 1024;
        unitIndex++;
    }
    return String.format("%d %s", sizeInBytes, units[unitIndex]);
}

파일 사이즈를 얻는 것은 디스크 io가 발생하므로 사이트 접속시 마다 구하는 것은 좋지 않습니다.

Leave a Comment