B4J Question List files in folder by file size

ElliotHC

Active Member
Licensed User
Hi,

I am using the wcl example to sort files in a folder by size. (this might not be the easiest way to do it)
There are a number of text files in a folder that are all named by date, but I don't want to work through them by name, I need to work through them but in order of data size with the largest file first.
Does anyone know the most efficient way of doing this?

Here is my code

Sort Files:
wcl.ListFiles("C:\PULSE",True, "*.txt",True, False)

    For Each item In wcl.FileListing
        Dim File_Size As Int
        File_Size = File.Size("",item)
        fx.Msgbox(MainForm,File_Size,"")
    Next

This however doesn't seem to list them in size.

Thanks in advance
 

ElliotHC

Active Member
Licensed User
I have managed to sort in size order like this, but this can't be the most efficient way of doing it?
TSorter is a 1ms timer.

TSorter:
Sub TSorter_Tick
   
Dim To_Remove As Int
Dim Item_Count As Int
    Largest = 0
    If  UnSorted.Size > 0 Then
    For Each Item In UnSorted
       
        Dim File_Size As Int
        File_Size = File.Size("",Item)
    If Largest < File_Size Then
        Largest_String = Item
        Largest = File_Size
        To_Remove = Item_Count
    End If
    Item_Count = Item_Count + 1
        'fx.Msgbox(MainForm,File_Size,"")
    Next
    'fx.Msgbox(MainForm,Largest_String,"")
    UnSorted.RemoveAt(To_Remove)
    Sorted.Add(Largest_String)
    ListView2.Items.Add(Largest_String)
    Else
        TSorter.Enabled = False
    End If
   
End Sub
 
Upvote 0

Heuristx

Active Member
Licensed User
Longtime User
Use a B4XOrderedMap:
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
B4X:
Sub Process_Globals
    Type FileItem (Dir As String, FileName As String, Size As Long, Date As Long)
End Sub

Sub AppStart (Args() As String)
    Dim files As List = ListFolderSortedBySize("C:\Users\H\Downloads")
    For Each f As FileItem In files
        Log(f)
    Next
End Sub

Private Sub ListFolderSortedBySize(Folder As String) As List
    Dim res As List
    res.Initialize
    For Each f As String In File.ListFiles(Folder)
        res.Add(CreateFileItem(Folder, f, File.Size(Folder, f), File.LastModified(Folder, f)))        
    Next
    res.SortType("Size", True)
    Return res
End Sub

Public Sub CreateFileItem (Dir As String, FileName As String, Size As Long, Date As Long) As FileItem
    Dim t1 As FileItem
    t1.Initialize
    t1.Dir = Dir
    t1.FileName = FileName
    t1.Size = Size
    t1.Date = Date
    Return t1
End Sub
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…