How do you get the size of a file in bytes using Java?

Java MCQ: How do you get the size of a file in bytes using Java?

a) getSize()
b) size()
c) length()
d) fileSize()

Answer:

c) length()

Explanation:

The length() method in Java is used to get the size of a file in bytes. It is a method of the File class, which is part of the java.io package. This method returns the size of the file in bytes as a long value.

Here’s an example of how to use the length() method to get the size of a file:

import java.io.File;

public class GetFileSizeExample {
    public static void main(String[] args) {
        File file = new File("example.txt");
        if (file.exists()) {
            long fileSize = file.length();
            System.out.println("File size in bytes: " + fileSize);
        } else {
            System.out.println("File does not exist.");
        }
    }
}

In this example, a File object is created to represent the file example.txt. The length() method is then called on this object to get the file size in bytes. The size is printed to the console. If the file does not exist, a message indicating this is printed.

The length() method is essential for file management tasks where knowing the file size is necessary, such as when monitoring file sizes, managing storage space, or preparing files for transfer.

This method is straightforward and effective for determining the size of a file, making it a commonly used tool in Java file handling.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top