Android Question [ExternalStorage] How to read a file as bytes from USB stick?

prbmjr

Member
Licensed User
Hi every one!

I need to read a file from a USB stick as bytes using the ExternalStorage library, I had the follow code:

B4X:
Public Storage As ExternalStorage
Public randomfile As ExternalFile

Storage.Initialize (Me, "Storage")

B4XPages.MainPage.Storage.SelectDir(True)

Wait For Storage_ExternalFolderAvailable

B4XPages.MainPage.randomfile.Initialize
   
B4XPages.MainPage.randomfile = B4XPages.MainPage.Storage.FindDirOrCreate(B4XPages.MainPage.Storage.Root,"RANDOMKEY")

If B4XPages.MainPage.randomfile.IsInitialized Then
   
    Dim inputstream As InputStream = B4XPages.MainPage.Storage.OpenInputStream(B4XPages.MainPage.randomfile)
               
    inputstream.ReadBytes(buffer,0,inputstream.BytesAvailable)
   
    Dim RndFileObj As B4XBytesBuilder
    RndFileObj.Initialize
   
    RndFileObj.Append(buffer)

end if

My question is: This is the best/optmized way to read a file as bytes from a USB stick?

Thank you in advance!
 

prbmjr

Member
Licensed User
No. Better:
B4X:
Dim b() As Byte = Bit.InputStreamToBytes(inputstream)

BytesAvailable is only an estimation and can return less than the complete size.

Perfect EREL!

You took the words from my mouth!! When I will post exactly these ajustments in my previous code, I saw that you posted first, you are Amazing!!

Thanks for existing Erel!!

br,

Paulo Bueno
 
Upvote 0
Top