어제 오늘 내일

[Java] 파일 사이즈 구하는 3가지 방법 본문

IT/Java

[Java] 파일 사이즈 구하는 3가지 방법

hi.anna 2021. 5. 30. 08:53

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

  1. Files
  2. FileChannel
  3. File

 

 

1. Files

public static long size​(Path path) throws IOException

java.nio.file.Files 클래스의 size() 메소드는

파일의 크기를 byte단위로 리턴합니다.

 

  코드  

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:\\example\\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

public abstract long size() throws IOException

java.nio.channels.FileChannel 클래스의 size()는 byte 단위의 파일의 크기를 리턴합니다.

 

  코드  

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:\\example\\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

public long length()

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

 

  예제  

import java.io.File;
import java.io.IOException;
public class GetFileSize {
public static void main(String[] args) throws IOException {
File file = new File("d:\\example\\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
}
}

 


 

Files, FileChannel, File 클래스를 이용하여

파일 사이즈를 구하는 방법을 알아보았습니다.

 

 

반응형
Comments