Get file size

File meta data is stored within the file system and directories. It tracks information about each of the file which is typically referred to as file attributes. File attributes include size of a file, is it a directory, a symbolic link, a regular file, determine if the file is hidden, retrieve the last modified time and find when a file was created.

Setup

private static final String SOURCE = "com/levelup/java/io/get-file-size.txt";

Path source;

@Before
public void setUp () throws IOException, URISyntaxException {

    source = Paths.get(this.getClass().getClassLoader().getResource(SOURCE).toURI());    
}

Straight up Java

File.length

@Test
public void file_size () {

    File file = source.toFile();
    
    assertEquals(29, file.length());
}

Java 7 File I/O

@Test
public void file_size_nio () throws IOException {

    BasicFileAttributes attr = Files.readAttributes(source, BasicFileAttributes.class);

    long fileSize = attr.size();
    
    assertEquals(29, fileSize);
}

Apache Commons

@Test
public void file_size_apache_commons () {
    
    long fileSize = FileUtils.sizeOf(source.toFile());
    
    assertEquals(29, fileSize);
}