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
'Spring > Java' 카테고리의 다른 글
[ spring ] @RequestMapping 대신 @PostMapping @GetMapping 쓰는 이유 및 차이점 (0) | 2022.07.07 |
---|---|
[ Java ] String to int, int to String 형변환 (문자열을 숫자로 / 숫자를 문자열로 변환) (0) | 2022.04.22 |
[ java ] 파일 다운로드 완료 시 로딩바 종료 기능 - 세션 이용 (0) | 2022.04.20 |
[ Java ] 문자열 자르기 - Substring, Split (0) | 2022.04.15 |
[ Java / Spring ] 스케줄링(@Scheduled) 사용법 & 크론(cron) 표현식 (0) | 2022.04.11 |
댓글