Java에서 아래 클래스들을 이용하여 디렉토리, 파일 사이즈를 구하는 다양한 방법을 소개합니다.
- File
- Files, Paths
- Java8 Stream
- Commons-io 라이브러리
예제와 함께 알아보겠습니다.
File 클래스로 사이즈 계산
File.length()
는 파일의 크기를 리턴합니다. 단위는 byte입니다.
다음과 같이 파일 크기를 구할 수 있고, 다른 단위로 변환할 수도 있습니다.
File file = new File("/home/mjs/test/myfile/file1.txt");
if (file.exists()) {
double bytes = file.length();
double kilobytes = (bytes / 1024);
double megabytes = (kilobytes / 1024);
double gigabytes = (megabytes / 1024);
System.out.println("bytes : " + bytes);
System.out.println("kilobytes : " + kilobytes);
System.out.println("megabytes : " + megabytes);
System.out.println("gigabytes : " + gigabytes);
} else {
System.out.println("File does not exists!");
}
결과
bytes : 169439.0
kilobytes : 165.4677734375
megabytes : 0.1615896224975586
gigabytes : 1.5780236572027206E-4
terabytes : 1.541038727737032E-7
하지만 Folder에 대해서 위의 코드를 적용하면, Folder에 대한 파일 크기인 4096 byte만 리턴합니다.
아래 코드를 실행하면 /home/mjs/test/myfile
폴더 하위에 있는 파일 크기들은 계산되지 않고 4096 byte만 리턴됩니다.
System.out.println();
File folder = new File("/home/mjs/test/myfile");
double bytes = folder.length();
System.out.println("bytes : " + bytes);
// output:
// bytes : 4096.0
하위 파일들의 사이즈도 모두 계산하려면 다음과 같이 하위 파일을 모두 탐색하고 파일의 크기의 합을 구해야 합니다.
File folder = new File("/home/mjs/test/myfile");
long bytes = getFolderSize(folder);
System.out.println("bytes : " + bytes);
public static long getFolderSize(File folder) {
long length = 0;
File[] files = folder.listFiles();
int count = files.length;
for (int i = 0; i < count; i++) {
if (files[i].isFile()) {
length += files[i].length();
} else {
length += getFolderSize(files[i]);
}
}
return length;
}
위의 코드는 재귀적으로 파일을 탐색하도록 구현하였습니다.(recursive)
결과
bytes : 7119049
Files를 이용하여 파일 사이즈 계산
Java7의 Files를 이용하여 디렉토리를 탐색할 수 있습니다. 탐색하면서 폴더가 아니고 파일인 경우, 그 크기를 더하면 됩니다.
다음 코드는 myfile 폴더의 크기를 계산하는 예제입니다.
Path folder = Paths.get("/home/mjs/test/myfile");
AtomicLong bytes = new AtomicLong(0);
try {
Files.walkFileTree(folder, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
bytes.addAndGet(attrs.size());
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("bytes : " + bytes);
결과
bytes : 7119049
Stream을 이용하여 파일 사이즈 계산
Files 클래스는 Files.walk()
메소드를 제공합니다. 이 메소드는 인자로 전달되는 폴더에 대한 하위 파일을 Stream<Path>
타입으로 리턴합니다.
다음과 같이 Stream에서 파일들만 필터링하여 파일 크기의 합을 구할 수 있습니다.
Path folder = Paths.get("/home/mjs/test/myfile");
try {
long bytes = Files.walk(folder)
.filter(p -> p.toFile().isFile())
.mapToLong(p -> p.toFile().length())
.sum();
System.out.println("bytes : " + bytes);
} catch (IOException e) {
e.printStackTrace();
}
결과
bytes : 7119049
Commons-io를 이용하여 파일 사이즈 계산
Commons-io 라이브러리를 이용하면 더 간단하게 디렉토리의 크기를 구할 수 있습니다.
Commons-io를 사용하려면, Gradle 프로젝트의 경우 build.gradle
의 dependencies에 다음과 같이 추가합니다.
dependencies {
compile group: 'commons-io', name: 'commons-io', version: '2.6'
...
}
Maven 등의 다른 빌드시스템을 사용하는 프로젝트는 mvnrepository.com을 참고하셔서 설정하시면 됩니다.
다음은 디렉토리의 파일 크기를 계산하는 코드입니다.
File folder = new File("/home/mjs/test/myfile");
long bytes = FileUtils.sizeOfDirectory(folder);
System.out.println("bytes : " + bytes);
FileUtils.sizeOfDirectory()
의 인자로 전달되는 디렉토리의 파일 크기를 byte로 리턴합니다.
결과
bytes : 7119049