How do I get file size?

This example will show you how to get the size of a file. To obtain the size of a file you can use the File‘s length() method. This method return the file size in bytes.



public class FileSize {
    public static void main(String[] args) throws Exception {
        File file = new File("kodejava.html");

        // Get the size of a file in bytes.
        long fileSize = file.length();

        // Using new features in Java to print the file size
        System.out.printf("File size: %,d bytes.%n", fileSize);

This will print something like:

File size: 107,101 bytes.

How do I know the size of ArrayList?

In this example we are going to learn how to obtain the size of an ArrayList object. As you might already know, anĀ java.util.ArrayList is a class that can be use to create a dynamic size array. We can add and remove elements from the ArrayList dynamically.

Because its elements can be add or remove at anytime, we might want to know the number of elements currently stored in this list. To obtain the size we can use the size() method. This method returns an int value that tells us the number of elements stored in the ArrayList object.

When the list contains more than Integer.MAX_VALUE elements this method returns Integer.MAX_VALUE.

package org.kodejava.example.util;

import java.util.ArrayList;
import java.util.List;

public class ArrayListSize {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Item 1");
        list.add("Item 2");
        list.add("Item 3");

        int size = list.size();
        System.out.println("List size = " + size);

In the code snippet above we start creating an instance of ArrayList that can holds String values. As a good practice we should always use the interface as the type of the declared object, in this case we use the List interface. The <> is a diamond operator, started from JDK 7 you can use this operator so that you don’t need to repeat the generic type twice between the declaration and instantiation.

After we create the ArrayList object and add string elements to the list object, we get the size of the list by calling the size() method. We store the result in the size variable and print out its value. If you compile an run the code above you will get the following output:

List size = 3