Home > Java > javaTutorial > body text

How to Calculate the Size of a File or Folder in Java?

DDD
Release: 2024-10-30 21:21:30
Original
203 people have browsed it

How to Calculate the Size of a File or Folder in Java?

Calculating File and Folder Size in Java

Determining the size of files and folders is a fundamental task in programming. Java provides convenient methods for retrieving this information.

Retrieving File Size

To obtain the size of a file, utilize the File class:

<code class="java">java.io.File file = new java.io.File("myfile.txt");
long fileSize = file.length();</code>
Copy after login

This method returns the file size in bytes or 0 if the file doesn't exist.

Calculating Folder Size

Java doesn't provide a direct mechanism for determining the size of a folder. To accomplish this, we can recursively traverse the directory tree using the listFiles() method. Here's a sample function:

<code class="java">public static long folderSize(File directory) {
    long size = 0;
    for (File file : directory.listFiles()) {
        if (file.isFile())
            size += file.length();
        else
            size += folderSize(file);
    }
    return size;
}</code>
Copy after login

This function calculates the folder size by recursively adding the sizes of its files and subfolders.

Caution:

Note that the folderSize() method has limitations. It may encounter null references from listFiles() and overlook symlinks. For reliable results, consider using a robust implementation designed for production use.

The above is the detailed content of How to Calculate the Size of a File or Folder in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!