B4J Code Snippet Folder size

Author: Erel

Note that it ignores subfolders.

B4X:
Sub SizeOfFilesInFolder(f As String) As Long
   Dim total As Long
   For Each filename As String In File.ListFiles(f)
     If File.IsDirectory(f, filename) = False Then
       total = total + File.Size(f, filename)
     End If
   Next
   Return total
End Sub
 

Daestrum

Expert
Licensed User
Longtime User
I will try and help
B4X:
#if java
import java.io.*;
import java.nio.file.*;
public static long folderSize(String pth) throws IOException {
    Path folder = Paths.get(pth);
    long size = Files.walk(folder)
      .filter(p -> p.toFile().isFile())
      .mapToLong(p -> p.toFile().length())
      .sum();
    return size / 1_048_576;  // (MiB)
}
#end if

Is called from B4J as
B4X:
' various ways to do this
Dim myFolderSize As Long = (Me).As(JavaObject).RunMethod("folderSize",Array("yourPath"))

If you want to see under 1MiB folders change the return line to
B4X:
return (size < 1_048_576) ? size : (size / 1_048_576);
 
Last edited:

MrKim

Well-Known Member
Licensed User
Longtime User
Windows 7 Explorer. When I hover the mouse cursor over a folder, sometimes a popup appears giving me the size of it but not always :oops: :mad:. So I'm afraid I'll have to develop a little (B4J) tool that lists the folder names and their size.
Right click and select properties will give you the size.
 

PaulMeuris

Well-Known Member
Licensed User
Using a recursive sub in B4J will do the same as the Java code @Daestrum showed.
After a few tests i have found that the Java code is a little bit faster.
In the Java code there is no test for the permissions (java.nio.file.AccessDeniedException).
The first calculation takes longer than the second calculation for the same folder.
Here's the compact version in B4J without the extra tests for comparison.
B4X:
Private Sub get_size_of_folder(folder As String) As Long
    Dim lst As List = File.ListFiles(folder)
    Dim fsize As Long
    For i = 0 To lst.Size-1
        If File.IsDirectory(folder, lst.Get(i)) Then
            Dim subfolder As String = folder & "\" & lst.Get(i)
            fsize = fsize + get_size_of_folder(subfolder)
        Else
            fsize = fsize + File.Size(folder, lst.Get(i))
        End If
    Next
    Return fsize
End Sub
Calculating the size of a root (drive) folder (c:\ or e:\) will take a long time...
 
Last edited:
Top