Skip to content

kiwi.io.FileInputStream

Nikos Siatras edited this page Oct 10, 2022 · 12 revisions

The FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment.

The FileInputStream class exists in the kiwi/io/FileInputStream.bi file.

FileInputStream Class Methods

Method Description
FileInputStream .OpenStream() Opens a file Input Stream and returns true if file exists and can be read
FileInputStream .CloseStream() Closes the file Input Stream
FileInputStream .read() Reads a single byte. Returns the byte read, or -1 if the end of the stream has been reached
FileInputStream .readAllBytes(dataArray() as UByte) Reads all file bytes into the given byte array and returns true. If the file is not available then it returns false. Introduced in Kiwi 1.0.2
FileInputStream .reset() Resets the stream and the file can be readed again.

FileInputStream Examples

Example - Read all file data

The following example uses the FileInputStream.readAllBytes() method to read all file bytes and push them into an array.
The FileInputStream.readAllBytes() is the fastest method to load binary into RAM.

#include once "kiwi\kiwi.bi"
#include once "kiwi\io.bi" ' Include Kiwi's IO package

' Initialize a file and a FileInput stream
Dim myFile as File = File("C:\Users\nsiat\Desktop\MyFile.zip")
Dim reader as FileInputStream = FileInputStream(myFile) 

' Declare a UByte array to push the file bytes
Dim As UByte dataArray() 

' Ask FileInputStream to push all file bytes into dataArray() 
if reader.readAllBytes(dataArray()) then
    print "Total bytes read: " & ubound(dataArray)+1
else
    print "Unable to open the file!"
end if

Example - Read a file Byte-by-Byte

The following example code will reads a file byte-by-byte into a Byte array.

#include once "kiwi\kiwi.bi"
#include once "kiwi\io.bi" ' Include Kiwi's IO package

' Initialize the file to read and a FileInputStream
Dim myFile as File = File("C:\Users\nsiat\Desktop\MyFile.zip")
Dim reader as FileInputStream = FileInputStream(myFile) 

Dim byteCounter as LongInt = 0

' Try to open the Stream
if reader.OpenStream() = true then

    ' Create an array to hold file bytes
    ' Caution: This array has to be declared as Ubyte
    Dim fileData(myFile.getSize()) as UByte

    Dim byteRead as Integer = reader.read()
    while (byteRead > - 1)
        byteCounter += 1 
        fileData(byteCounter) = CAST(Byte, byteRead)
        byteRead = reader.read()
    wend
    
    ' Close the Stream
    reader.CloseStream()
    
    print "Total bytes read: " & byteCounter
else
    print "Unable to open the file!"
end if