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

RandomAccessFile

List of types:

AsyncStreams
B4XSerializator
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.
NewStream event is only raised in prefix mode when the other side sends a stream with WriteStream. This event is raised after the complete stream was received successfully.
The event includes the saved stream folder and name. Note that the file name is an arbitrary string.

Events:

NewData (Buffer() As Byte)
Error
Terminated
NewStream (Dir As String, FileName As String)

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]

  SendAllAndClose As Boolean

  StreamFolder As String

  StreamReceived As Long [read only]

  StreamTotal As Long [read only]

  Write (Buffer() As Byte) As Boolean

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

  WriteStream (In As java.io.InputStream, Size As Long) As 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.
SendAllAndClose As Boolean
Sends a message to the internal queue. AsyncStreams will be closed when the message is processed.
The Terminated event will be raised.
Returns False if the queue is full or the connection is not open.
StreamFolder As String
Received streams will be saved in this folder.
StreamReceived As Long [read only]
Returns the number of bytes of the currently received file. Only valid in prefix mode.
StreamTotal As Long [read only]
Returns the total number of bytes of the currently received file. Only valid in prefix mode.
Write (Buffer() As Byte) As 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 Int) As 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.
WriteStream (In As java.io.InputStream, Size As Long) As Boolean
Writes the given stream. This method is only supported in prefix mode.
The checksum will be calculated and sent to the other size. The NewStream event will be raised, in the receiving side, after the stream was received successfully.
This method is more efficient than sending the same data in chunks. It can handle streams of any size.
In - InputStream that will be read. Note that the InputStream will be closed after the stream is sent.
Size - Number of bytes to read from the stream.

B4XSerializator


Events:

ObjectToBytes (Success As Boolean, Bytes() As Byte)
BytesToObject (Success As Boolean, NewObject As Object)

Members:


  ConvertBytesToObject (Bytes() As Byte) As Object

  ConvertBytesToObjectAsync (Bytes() As Byte, EventName As String)

  ConvertObjectToBytes (Object As Object) As Byte()

  ConvertObjectToBytesAsync (Object As Object, EventName As String)

  Tag As Object

Members description:

ConvertBytesToObject (Bytes() As Byte) As Object
In-memory version of RandomAccessFile.ReadB4XObject.
ConvertBytesToObjectAsync (Bytes() As Byte, EventName As String)
Asynchronously converts the bytes to object. The BytesToObject event will be raised when the object is ready.
Do not reuse the same B4XSerializator instance when calling asynchronous methods.
ConvertObjectToBytes (Object As Object) As Byte()
In-memory version of RandomAccessFile.WriteB4XObject.
The following types are supported: Lists, Arrays of bytes and Arrays of objects, Maps, Strings, primitive types and user defined types.
Note that user defined types should be declared in the Main module.
ConvertObjectToBytesAsync (Object As Object, EventName As String)
Asynchronously converts the object to bytes. The ObjectToBytes event will be raised with the serialized bytes.
Do not reuse the same B4XSerializator instance when calling asynchronous methods.
Tag As Object
Gets or sets the Tag value. This is a place holder that can used to store additional 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 String) As Byte()

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

  WrapInputStream (In As java.io.InputStream, CompressMethod As String) As InputStreamWrapper

  WrapOutputStream (Out As java.io.OutputStream, CompressMethod As String) As OutputStreamWrapper

Members description:

CompressBytes (Data() As Byte, CompressMethod As String) As 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 String) As 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 String) As 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 String) As 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 Int) As 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 Int) As 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)

  ReadB4XObject (Position As Long) As Object

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

  ReadDouble (Position As Long) As Double

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

  ReadFloat (Position As Long) As Float

  ReadInt (Position As Long) As Int

  ReadLong (Position As Long) As Long

  ReadObject (Position As Long) As Object

  ReadShort (Position As Long) As Short

  ReadSignedByte (Position As Long) As Byte

  ReadUnsignedByte (Position As Long) As Int

  Size As Long [read only]

  WriteB4XObject (Object As Object, Position As Long)

  WriteByte (Byte As Byte, Position As Long)

  WriteBytes (Buffer() As Byte, StartOffset As Int, Length As Int, Position As Long) As 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.
ReadB4XObject (Position As Long) As Object
Reads an object previously written with WriteB4XObject.
ReadBytes (Buffer() As Byte, StartOffset As Int, Length As Int, Position As Long) As 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 to Length (unless the file is smaller than the requested length).
ReadDouble (Position As Long) As Double
Reads a Double value stored in the specified position.
Reads 8 bytes.
ReadEncryptedObject (Password As String, Position As Long) As Object
Reads an encrypted object from the stream.
Password - The password used while writing the object.
Position - Stream position.
ReadFloat (Position As Long) As Float
Reads a Float value stored in the specified position.
Reads 4 bytes.
ReadInt (Position As Long) As Int
Reads an Int value stored in the specified position.
Reads 4 bytes.
ReadLong (Position As Long) As Long
Reads a Long value stored in the specified position.
Reads 8 bytes.
ReadObject (Position As Long) As Object
Reads an object from the stream.
See WriteObject for supported types.
ReadShort (Position As Long) As Short
Reads a Short value stored in the specified position.
Reads 2 bytes.
ReadSignedByte (Position As Long) As Byte
Reads a signed byte (-128 - 127) stored in the specified position.
ReadUnsignedByte (Position As Long) As 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.
WriteB4XObject (Object As Object, Position As Long)
Similar to WriteObject. This method writes the object in a format supported by B4i, B4A and B4J.
The following types are supported: Lists, Arrays of bytes and Arrays of objects, Maps, Strings, primitive types and user defined types.
Note that user defined types should be declared in the Main module.
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 Long) As 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 which is equal to Length.
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