본문 바로가기
Spring/Java

[ Java ] 파일 사이즈 구하기 (Files, FileChannel, File)

by snow_hong 2022. 4. 21.

Java API를 이용해서 파일의 크기를 구하는 3가지 방법을 소개합니다.

1. Files

더보기

java.nio.file.Files클래스의 size()메소드파일의 크기를 byte단위로 리턴

public static long size(Path path) throws IOException

 

 코드 

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class GetFileSize {

public static void main(String[] args) throws IOException {

Path path = Paths.get("d:\\test\\image.jpg");

long bytes = Files.size(path);
long kilobyte = bytes / 1024;
long megabyte = kilobyte / 1024;

System.out.println(bytes + " byte"); // 3980059 byte
System.out.println(kilobyte + " kb"); // 3886 kb
System.out.println(megabyte + " mb"); // 3 mb

}
}

 

2. FileChannel

더보기

java.nio.channels.FileChannel 클래스의 size() 메소드파일의 크기를 byte단위로 리턴

public abstract long size() throws IOException

 

 코드 

import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;

public class GetFileSize {
public static void main(String[] args) throws IOException {

Path path = Paths.get("d:\\test\\image.jpg");

FileChannel fileChannel = FileChannel.open(path);
long bytes = fileChannel.size();

long kilobyte = bytes / 1024;
long megabyte = kilobyte / 1024;

System.out.println(bytes + " byte"); // 3980059 byte
System.out.println(kilobyte + " kb"); // 3886 kb
System.out.println(megabyte + " mb"); // 3 mb

}
}

 

3. File

더보기

java.io.File의 length() 메소드파일의 크기를 byte단위로 리턴

public long length()

 

 코드 

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

public class GetFileSize {
public static void main(String[] args) throws IOException {

File file = new File("d:\\test\\image.jpg");

long bytes = file.length();
long kilobyte = bytes / 1024;
long megabyte = kilobyte / 1024;

System.out.println(bytes + " byte"); // 3980059 byte
System.out.println(kilobyte + " kb"); // 3886 kb
System.out.println(megabyte + " mb"); // 3 mb

}
}

 

 

728x90

댓글