Android Programming Press on the image to return to the main documentation page.

RandomAccessFile

List of types:

AsyncStreams
CompressedStreams
CountingInputStream
CountingOutputStream
RandomAccessFile

AsyncStreams

The AsyncStreams object allows you to read from an InputStream and write to an OutputStream in the background without blocking the main thread.
See the AsyncStreams Tutorial.
NewData event is raised when new data is available.
Error event is raised when an error was encountered. You should check LastException to find the error.
Terminated event is raised when the other side has terminated the connection.

Events:

NewData (Buffer() As Byte)
Error
Terminated

Members:


  Close

  Initialize (In As java.io.InputStream, Out As java.io.OutputStream, EventName As String)

  InitializePrefix (In As java.io.InputStream, BigEndian As Boolean, Out As java.io.OutputStream, EventName As String)

  IsInitialized As Boolean

  OutputQueueSize As Int  [read only]

  Write (Buffer() As ByteAs Boolean

  Write2 (Buffer() As Byte, Start As Int, Length As IntAs Boolean

Members description:

Close
Closes the associated streams.
Initialize (In As java.io.InputStream, Out As java.io.OutputStream, EventName As String)
Initializes the object. Unlike in prefix mode, the NewData event will be raised with new data as soon as it is available.
In - The InputStream that will be read. Pass Null if you only want to write with this object.
Out - The OutputStream that is used for writing the data. Pass Null if you only want to read with this object.
EventName - Determines the Subs that handle the NewData and Error events.
InitializePrefix (In As java.io.InputStream, BigEndian As Boolean, Out As java.io.OutputStream, EventName As String)
Initializes the object and sets it in "prefix" mode. In this mode incoming data should adhere to the following protocol:
Every message begins with the message length as an Int value (4 bytes). This length should not include the additional 4 bytes.
The NewData event will be raised only with full messages (not including the 4 bytes length value).
The prefix Int value will be added to the output messages automatically.
This makes it easier as you do not need to deal with broken messages.
In - The InputStream that will be read. Pass Null if you only want to write with this object.
BigEndian - Whether the length value is encoded in BigEndian or LittleEndian.
Out - The OutputStream that is used for writing the data. Pass Null if you only want to read with this object.
EventName - Determines the Subs that handle the NewData and Error events.
IsInitialized As Boolean
Tests whether this object has been initialized.
OutputQueueSize As Int  [read only]
Returns the number of messages waiting in the output queue.
Write (Buffer() As ByteAs Boolean
Adds the given bytes array to the output stream queue.
If the object was initialized with InitializePrefix then the array length will be added before the array.
Returns False if the queue is full and it is not possible to queue the data.
Write2 (Buffer() As Byte, Start As Int, Length As IntAs Boolean
Adds the given bytes array to the output stream queue.
If the object was initialized with InitializePrefix then the array length will be added before the array.
Returns False if the queue is full and it is not possible to queue the data.

CompressedStreams

CompressedStreams object allows you to compress and decompress data using gzip or zlib compression methods.
There are two options for working with CompressedStreams:
Wrapping another stream by calling WrapInputStream or WrapOutputStream.
Compressing or decompressing the data in memory.
The following example demonstrates the usage of this object:
Sub Globals

End Sub

Sub Activity_Create(FirstTime As Boolean)
    
Dim sb As StringBuilder
    sb.Initialize
    
'Concatenation operations are much faster with StringBuilder than with String.
    For i = 1 To 10000
        sb.Append(
"Playing with compressed streams.").Append(CRLF)
    
Next
    
Dim out As OutputStream
    
Dim s As String
    
Dim compress As CompressedStreams
    s = sb.ToString
    
'Write the string without compressing it (we could have used File.WriteString instead).
    out = File.OpenOutput(File.DirRootExternal, "test.txt", False)
    WriteStringToStream(out, s)
    
    
'Write the string with gzip compression.
    out = File.OpenOutput(File.DirRootExternal, "test.gz", False)
    out = compress.WrapOutputStream(out, 
"gzip")
    WriteStringToStream(out, s)
    
    
'Write the string with zlib compression
    out = File.OpenOutput(File.DirRootExternal, "test.zlib", False)
    out = compress.WrapOutputStream(out, 
"zlib")
    WriteStringToStream(out, s)
    
    
'Show the files sizes
    Msgbox("No compression: " & File.Size(File.DirRootExternal, "test.txt") & CRLF _
        & 
"Gzip: " & File.Size(File.DirRootExternal, "test.gz") & CRLF _
        & 
"zlib: " & File.Size(File.DirRootExternal, "test.zlib"), "Files sizes")

    
'Read data from a compressed file
    Dim in As InputStream
    in = File.OpenInput(File.DirRootExternal, 
"test.zlib")
    in = compress.WrapInputStream(in, 
"zlib")
    
Dim reader As TextReader
    reader.Initialize(in)
    
Dim line As String
    line = reader.ReadLine
    Msgbox(line, 
"First line")
    reader.Close
    
    
'In memory compression / decompression
    Dim data() As Byte
    data = 
"Playing with in-memory compression.".GetBytes("UTF8")
    
Dim compressed(), decompressed() As Byte
    compressed = compress.CompressBytes(data, 
"gzip")
    decompressed = compress.DecompressBytes(compressed, 
"gzip")
    
'In this case the compressed data is longer than the decompressed data.
    'The data is too short for the compression to be useful.
    Log("Compressed: " & compressed.Length) 
    Log(
"Decompressed: " & decompressed.Length)
    Msgbox(BytesToString(decompressed,
0, decompressed.Length, "UTF8"), "")
End Sub
Sub WriteStringToStream(Out As OutputStream, s As String)
    
Dim t As TextWriter
    t.Initialize(Out)
    t.Write(s)
    t.Close 
'Closes the internal stream as well
End Sub

Events:

None

Members:


  CompressBytes (Data() As Byte, CompressMethod As StringAs Byte()

  DecompressBytes (CompressedData() As Byte, CompressMethod As StringAs Byte()

  WrapInputStream (In As java.io.InputStream, CompressMethod As StringAs InputStreamWrapper

  WrapOutputStream (Out As java.io.OutputStream, CompressMethod As StringAs OutputStreamWrapper

Members description:

CompressBytes (Data() As Byte, CompressMethod As StringAs Byte()
Returns a byte array with the compressed data.
Data - Data to compress.
CompressMethod - The name of the compression method (gzip or zlib).
DecompressBytes (CompressedData() As Byte, CompressMethod As StringAs Byte()
Returns a byte array with the decompressed data.
CompressedData - The compressed data that should be decompressed.
CompressMethod - The name of the compression method (gzip or zlib).
WrapInputStream (In As java.io.InputStream, CompressMethod As StringAs InputStreamWrapper
Wraps an input stream and returns an input stream that automatically decompresses the stream when it is read.
In - The original input stream.
CompressMethod - The name of the compression method (gzip or zlib).
WrapOutputStream (Out As java.io.OutputStream, CompressMethod As StringAs OutputStreamWrapper
Wraps an output streams and returns an output stream that automatically compresses the data when it is written to the stream.
Out - The original output stream.
CompressMethod - The name of the compression method (gzip or zlib).

CountingInputStream

CountingInputStream and CountingOutputStream allow you to monitor the reading or writing progress.
Counting streams wrap the actual stream and provide a Count property which allows you to get the number of bytes read or written.
Counting streams are useful when the reading or writing operations are done in the background. You can then use a timer to monitor the progress.
This example logs the downloading progress:

Sub Process_Globals
    
Dim hc As HttpClient
    
Dim cout As CountingOutputStream
    
Dim length As Int
    
Dim timer1 As Timer
End Sub
Sub Globals

End Sub
Sub Activity_Create(FirstTime As Boolean)
    
If FirstTime Then
        hc.Initialize(
"hc")
        timer1.Initialize(
"Timer1"500)
    
End If
    
Dim req As HttpRequest
    req.InitializeGet(
"http://www.basic4ppc.com/android/files/b4a-trial.zip")
    hc.Execute(req, 
1)
End Sub

Sub hc_ResponseSuccess (Response As HttpResponse, TaskId As Int)
    cout.Initialize(File.OpenOutput(File.DirRootExternal, 
"1.zip", False))
    Timer1.Enabled = True
    length = Response.ContentLength
    Response.GetAsynchronously(
"response", cOut, True, TaskId)
End Sub

Sub hc_ResponseError (Response As HttpResponse, Reason As String, StatusCode As Int, TaskId As Int)
    Log(
"Error: " & Reason)
    
If Response <> Null Then
        Log(Response.GetString(
"UTF8"))
        Response.Release
    
End If
End Sub

Sub Response_StreamFinish (Success As Boolean, TaskId As Int)
    timer1.Enabled = False
    
If Success Then
        Timer1_Tick 
'Show the current counter status
        Log("Success!")
    
Else
        Log(
"Error: " & LastException.Message)
    
End If
End Sub

Sub Timer1_Tick
    Log(cout.Count & 
" out of " & length)
End Sub

Events:

None

Members:


  BytesAvailable As Int

  Close

  Count As Long

  Initialize (InputStream As java.io.InputStream)

  IsInitialized As Boolean

  ReadBytes (arg0() As Byte, arg1 As Int, arg2 As IntAs Int

Members description:

BytesAvailable As Int
Close
Count As Long
Gets or sets the number of bytes read.
Initialize (InputStream As java.io.InputStream)
Initializes the counting stream by wrapping the given input stream.
IsInitialized As Boolean
ReadBytes (arg0() As Byte, arg1 As Int, arg2 As IntAs Int

CountingOutputStream

See CountingInputStream for more information.

Events:

None

Members:


  Close

  Count As Long

  Flush

  Initialize (OutputStream As java.io.OutputStream)

  IsInitialized As Boolean

  ToBytesArray As Byte()

  WriteBytes (arg0() As Byte, arg1 As Int, arg2 As Int)

Members description:

Close
Count As Long
Gets or sets the number of bytes written.
Flush
Initialize (OutputStream As java.io.OutputStream)
Initializes the counting stream by wrapping the given output stream.
IsInitialized As Boolean
ToBytesArray As Byte()
WriteBytes (arg0() As Byte, arg1 As Int, arg2 As Int)

RandomAccessFile

This object allows you to non-sequentially access files and bytes arrays.
You can also use it to encode numbers to bytes (and vice versa).
Note that assets files (files added with the file manager) cannot be opened with this object as those files are actually packed inside the APK file.
A short tutorial about the encryption methods is available here.

Events:

None

Members:


  Close

  CurrentPosition As Long

  Flush

  Initialize (Dir As String, File As String, ReadOnly As Boolean)

  Initialize2 (Dir As String, File As String, ReadOnly As Boolean, LittleEndian As Boolean)

  Initialize3 (Buffer() As Byte, LittleEndian As Boolean)

  ReadBytes (Buffer() As Byte, StartOffset As Int, Length As Int, Position As LongAs Int

  ReadDouble (Position As LongAs Double

  ReadEncryptedObject (Password As String, Position As LongAs Object

  ReadFloat (Position As LongAs Float

  ReadInt (Position As LongAs Int

  ReadLong (Position As LongAs Long

  ReadObject (Position As LongAs Object

  ReadShort (Position As LongAs Short

  ReadSignedByte (Position As LongAs Byte

  ReadUnsignedByte (Position As LongAs Int

  Size As Long  [read only]

  WriteByte (Byte As Byte, Position As Long)

  WriteBytes (Buffer() As Byte, StartOffset As Int, Length As Int, Position As LongAs Int

  WriteDouble (Value As Double, Position As Long)

  WriteEncryptedObject (Object As Object, Password As String, Position As Long)

  WriteFloat (Value As Float, Position As Long)

  WriteInt (Value As Int, Position As Long)

  WriteLong (Value As Long, Position As Long)

  WriteObject (Object As Object, Compress As Boolean, Position As Long)

  WriteShort (Value As Short, Position As Long)

Members description:

Close
Closes the stream.
CurrentPosition As Long
Holds the current file position.
This value is updated automatically after each read or write operation.
Flush
Flushes any cached data.
Initialize (Dir As String, File As String, ReadOnly As Boolean)
Opens the specified file.
Note that it is not possible to open a file saved in the assets folder with this object.
If needed you can copy the file to another location and then open it.
ReadOnly - Whether to open the file in read only mode (otherwise it will be readable and writable).
Example:
Dim raf As RandomAccessFile
raf.Initialize(File.DirInternal, 
"1.dat", false)
Initialize2 (Dir As String, File As String, ReadOnly As Boolean, LittleEndian As Boolean)
Same as Initialize with the option to set the byte order to little endian instead of the
default big endian. This can be useful when sharing files with Windows computers.
Initialize3 (Buffer() As Byte, LittleEndian As Boolean)
Treats the given buffer as a random access file with a constant size.
This allows you to read and write values to an array of bytes.
ReadBytes (Buffer() As Byte, StartOffset As Int, Length As Int, Position As LongAs Int
Reads bytes from the stream and into to the given array.
Buffer - Array of bytes where the data will be written to.
StartOffset - The first byte read will be written to Buffer(StartOffset).
Length - Number of bytes to read.
Position - The position of the first byte to read.
Returns the number of bytes read (which is equal or smaller than Length).
ReadDouble (Position As LongAs Double
Reads a Double value stored in the specified position.
Reads 8 bytes.
ReadEncryptedObject (Password As String, Position As LongAs Object
Reads an encrypted object from the stream.
Password - The password used while writing the object.
Position - Stream position.
ReadFloat (Position As LongAs Float
Reads a Float value stored in the specified position.
Reads 4 bytes.
ReadInt (Position As LongAs Int
Reads an Int value stored in the specified position.
Reads 4 bytes.
ReadLong (Position As LongAs Long
Reads a Long value stored in the specified position.
Reads 8 bytes.
ReadObject (Position As LongAs Object
Reads an object from the stream.
See WriteObject for supported types.
ReadShort (Position As LongAs Short
Reads a Short value stored in the specified position.
Reads 2 bytes.
ReadSignedByte (Position As LongAs Byte
Reads a signed byte (-128 - 127) stored in the specified position.
ReadUnsignedByte (Position As LongAs Int
Reads an unsigned bytes (0 - 255) stored in the specified position.
The value returned is of type Int as Byte can only store values between -128 to 127.
Size As Long  [read only]
Returns the file size.
WriteByte (Byte As Byte, Position As Long)
Writes a Byte value to the specified position.
Writes 1 byte.
WriteBytes (Buffer() As Byte, StartOffset As Int, Length As Int, Position As LongAs Int
Writes the given buffer to the stream. The first byte written is Buffer(StartOffset)
and the last is Buffer(StartOffset + Length - 1).
Returns the numbers of bytes written.
WriteDouble (Value As Double, Position As Long)
Writes a Double value to the specified position.
Writes 8 bytes.
WriteEncryptedObject (Object As Object, Password As String, Position As Long)
Similar to WriteObject. The object is encrypted with AES-256 and then written to the stream.
Note that it is faster to write a single large object compared to many smaller objects.
Object - The object that will be written.
Password - The password that protects the object.
Position - The position in the file that this object will be written to.
WriteFloat (Value As Float, Position As Long)
Writes a Float value to the specified position.
Writes 4 bytes.
WriteInt (Value As Int, Position As Long)
Writes an Int value to the specified position.
Writes 4 bytes.
WriteLong (Value As Long, Position As Long)
Writes a Long value to the specified position.
Writes 8 bytes.
WriteObject (Object As Object, Compress As Boolean, Position As Long)
Writes the given object to the stream.
This method is capable of writing the following types of objects: Lists, Arrays, Maps, Strings, primitive types and user defined types.
Combinations of these types are also supported. For example, a map with several lists of arrays can be written.
The element type inside a collection must be a String or primitive type.
Note that changing your package name may make older objects files unusable (requiring you to write them again).
Object - The object that will be written.
Compress - Whether to compress the data before writing it. Should be true in most cases.
Position - The position in the file that this object will be written to.
WriteShort (Value As Short, Position As Long)
Writes a Short value to the specified position.
Writes 2 bytes.
Top