1+ package com .baeldung .java8 ;
2+
3+ import static org .junit .Assert .assertEquals ;
4+
5+ import java .io .File ;
6+ import java .io .IOException ;
7+ import java .nio .channels .FileChannel ;
8+ import java .nio .file .Path ;
9+ import java .nio .file .Paths ;
10+ import org .apache .commons .io .FileUtils ;
11+ import org .junit .Before ;
12+ import org .junit .Test ;
13+
14+ public class JavaFileSizeUnitTest {
15+ private static final long EXPECTED_FILE_SIZE_IN_BYTES = 11 ;
16+ private String filePath ;
17+
18+ @ Before
19+ public void init () {
20+ final String separator = File .separator ;
21+ filePath = String .join (separator , new String [] { "src" , "test" , "resources" , "testFolder" , "sample_file_1.in" });
22+ }
23+
24+ @ Test
25+ public void whenGetFileSize_thenCorrect () {
26+ final File file = new File (filePath );
27+
28+ final long size = getFileSize (file );
29+
30+ assertEquals (EXPECTED_FILE_SIZE_IN_BYTES , size );
31+ }
32+
33+ @ Test
34+ public void whenGetFileSizeUsingNioApi_thenCorrect () throws IOException {
35+ final Path path = Paths .get (this .filePath );
36+ final FileChannel fileChannel = FileChannel .open (path );
37+
38+ final long fileSize = fileChannel .size ();
39+
40+ assertEquals (EXPECTED_FILE_SIZE_IN_BYTES , fileSize );
41+ }
42+
43+ @ Test
44+ public void whenGetFileSizeUsingApacheCommonsIO_thenCorrect () {
45+ final File file = new File (filePath );
46+
47+ final long size = FileUtils .sizeOf (file );
48+
49+ assertEquals (EXPECTED_FILE_SIZE_IN_BYTES , size );
50+ }
51+
52+ @ Test
53+ public void whenGetReadableFileSize_thenCorrect () {
54+ final File file = new File (filePath );
55+
56+ final long size = getFileSize (file );
57+
58+ assertEquals (EXPECTED_FILE_SIZE_IN_BYTES + " bytes" , FileUtils .byteCountToDisplaySize (size ));
59+ }
60+
61+ private long getFileSize (final File file ) {
62+ final long length = file .length ();
63+ return length ;
64+ }
65+ }
0 commit comments