Android Question Load binary fine, modify it and then save it

giggetto71

Active Member
Licensed User
Longtime User
Hello guys,
I have a binary file previously created and I am able to read it perfectly, the problem is that I would like after modying it, to save it again in the same place where it was.
here's the code I use to load it. as you can see in the comment if I try to use the the file.writebytes back to the same filename and dir I got from the ContentChooser I get an error.
Is there a simple way to accomplish this?
thanks

B4X:
    Dim CC As ContentChooser, TempDir2,TempFileName2 As String, b() As Byte    
  
    CC.Initialize("CC")
 
    TempDir2 = ""
    TempFileName2 = ""

    CC.Show("*/*", "Choose the binary file")
    Wait For CC_Result (Success As Boolean, Dir2 As String, FileName2 As String)
    If Success Then
       TempDir2 = Dir2
       TempFileName2 = FileName2       
    Else
       ToastMessageShow("No files selected. File not imported", True)
       Return
    End If
    
    b = File.ReadBytes(Dir2, FileName2)
    'make some     modification
    'if I try to:
    File.WriteBytes(Dir2,FileName2,b)
    ' I get a java.io.FileNotFoundException: ContentDir/content:/com.android.providers.downloads.documents/document/43: open failed: ENOENT (No such file or directory)
 

jkhazraji

Active Member
Licensed User
Longtime User
The problem is that the URI you get from the ContentChooser doesn't directly translate to a filesystem path you to which you can write:
B4X:
Dim CC As ContentChooser, TempUri As String, b() As Byte   
 
CC.Initialize("CC")
CC.Show("*/*", "Choose the binary file")
Wait For CC_Result (Success As Boolean, Dir2 As String, FileName2 As String)
If Success Then
    TempUri = FileName2 ' This is actually a content URI
    b = File.ReadBytes(Dir2, FileName2)
    
    ' Make some modifications to b()
    
    ' Save back to the original location
    WriteBytesToContentUri(Dir2, FileName2, b)
Else
    ToastMessageShow("No files selected. File not imported", True)
    Return
End If

Sub WriteBytesToContentUri(Dir As String, FileName As String, Data() As Byte)
    Dim r As Reflector
    Dim context As JavaObject
    context = r.GetContext
    Dim uri As JavaObject
    uri.InitializeNewInstance("android.net.Uri", Array("parse", "content://com.android.providers.downloads.documents/document/" & FileName.SubStringAfterLast("/")))
    
    Try
        Dim out As OutputStream
        out = context.RunMethod("getContentResolver", Null).RunMethod("openOutputStream", Array(uri))
        Dim outStream As OutputStreamWrapper
        outStream.Initialize(out)
        outStream.WriteBytes(Data, 0, Data.Length)
        outStream.Close
    Catch
        Log(LastException)
        ToastMessageShow("Error saving file: " & LastException.Message, True)
    End Try
End Sub
 
Upvote 0
Top