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 length of a string?

To get the length of a text specified in a String object we can use the String.length() method call. This method returns the string length as an int value. The length of the string is equals to the length of the sequence of characters represented by this string object.

package org.kodejava.example.lang;

public class StringLengthExample {
    public static void main(String[] args) {
        String name = "Kodejava";

        // Get the length of the string specified by the name
        // variable.
        int length = name.length();
        System.out.println("Length = " + length);

If you run this code you will get the following output:

Length = 8