Module io
API
Declarations
ballerina/io Ballerina library
Overview
This module provides file read/write APIs and console print/read APIs. The file APIs allow read and write operations on different kinds of file types such as bytes, text, CSV, JSON, and XML. Further, these file APIs can be categorized as streaming and non-streaming APIs.
The following diagram depicts the overview architecture of the I/O package.
The file I/O operations can be categorized further based on the serialization and deserialization types such as:
- Bytes I/O
- Strings I/O
- CSV I/O
- JSON I/O
- XML I/O
Console I/O
The console I/O APIs, which help you to read from the console as well as write to the console are as follows.
io:print
io:println
io:readln
Bytes I/O
The bytes I/O APIs provide the reading and writing APIs in both streaming and non-streaming ways. Those APIs are,
io:fileReadBytes
io:fileReadBlocksAsStream
io:fileWriteBytes
io:fileWriteBlocksFromStream
Strings I/O
The strings I/O APIs provide the reading and writing APIs in 3 different ways:
- Read the complete file content as a string and write a given string to a file
- Read the complete file content as a set of lines and write a given set of lines to a file
- Read the complete file content as a stream of lines and write a given stream of lines to a file
The strings I/O APIs are as follows:
io:fileReadString
io:fileReadLines
io:fileReadLinesAsStream
io:fileWriteLines
io:fileWriteLinesFromStream
CSV I/O
The CSV I/O APIs provide the reading and writing APIs in both streaming and non-streaming ways. Those APIs are:
io:fileReadCsv
io:fileReadCsvAsStream
io:fileWriteCsv
io:fileWriteCsvFromStream
JSON I/O
The JSON I/O APIs provide the reading and writing APIs for JSON content. Those APIs are:
io:fileReadJson
io:fileWriteJson
XML I/O
The XML I/O APIs provide the reading and writing APIs for XML content. Those APIs are:
io:fileReadXml
io:fileWriteXml
Functions
createReadableChannel
function createReadableChannel(byte[] content) returns ReadableByteChannel|Error
Creates an in-memory channel, which will be a reference stream of bytes.
var byteChannel = io:createReadableChannel(content);
Parameters
- content byte[] - Content, which should be exposed as a channel
Return Type
- ReadableByteChannel|Error - The
io:ReadableByteChannel
related to the given bytes or else anio:Error
if any error occurred
fileReadBlocksAsStream
Read the entire file content as a stream of blocks.
stream<io:Block, io:Error?>|io:Error content = io:fileReadBlocksAsStream("./resources/myfile.txt", 1000);
fileReadBytes
Read the entire file content as a byte array.
byte[]|io:Error content = io:fileReadBytes("./resources/myfile.txt");
Parameters
- path string - The path of the file
Return Type
- readonly & byte[]|Error - A read-only byte array or an
io:Error
fileReadCsv
function fileReadCsv(string path, int skipHeaders, typedesc<string[]|map<anydata>> returnType) returns returnType[]|Error
Read file content as a CSV. When the expected data type is record[], the first entry of the csv file should contain matching headers.
string[][]|io:Error content = io:fileReadCsv("./resources/myfile.csv"); record{}[]|io:Error content = io:fileReadCsv("./resources/myfile.csv");
Parameters
- path string - The CSV file path
- skipHeaders int (default 0) - Number of headers, which should be skipped prior to reading records
Return Type
- returnType[]|Error - The entire CSV content in the channel as an array of string arrays, array of Ballerina records or an
io:Error
fileReadCsvAsStream
function fileReadCsvAsStream(string path, typedesc<string[]|map<anydata>> returnType) returns stream<returnType, Error?>|Error
Read file content as a CSV. When the expected data type is stream<record, io:Error?>, the first entry of the csv file should contain matching headers.
stream<string[]|io:Error content = io:fileReadCsvAsStream("./resources/myfile.csv"); stream<record{}, io:Error?>|io:Error content = io:fileReadCsvAsStream("./resources/myfile.csv");
Parameters
- path string - The CSV file path
Return Type
- stream<returnType, Error?>|Error - The entire CSV content in the channel a stream of string arrays, Ballerina records or an
io:Error
fileReadJson
Reads file content as a JSON.
json|io:Error content = io:fileReadJson("./resources/myfile.json");
Parameters
- path string - The path of the JSON file
Return Type
- json|Error - The file content as a JSON object or an
io:Error
fileReadLines
Reads the entire file content as a list of lines.
The resulting string array does not contain the terminal carriage (e.g., \r
or \n
).
string[]|io:Error content = io:fileReadLines("./resources/myfile.txt");
Parameters
- path string - The path of the file
fileReadLinesAsStream
Reads file content as a stream of lines.
The resulting stream does not contain the terminal carriage (e.g., \r
or \n
).
stream<string, io:Error?>|io:Error content = io:fileReadLinesAsStream("./resources/myfile.txt");
Parameters
- path string - The path of the file
fileReadString
Reads the entire file content as a string
.
The resulting string output does not contain the terminal carriage (e.g., \r
or \n
).
string|io:Error content = io:fileReadString("./resources/myfile.txt");
Parameters
- path string - The path of the file
fileReadXml
Reads file content as an XML.
xml|io:Error content = io:fileReadXml("./resources/myfile.xml");
Parameters
- path string - The path of the XML file
fileWriteBlocksFromStream
function fileWriteBlocksFromStream(string path, stream<byte[], Error?> byteStream, FileWriteOption option) returns Error?
Write a byte stream to a file.
byte[] content = [[60, 78, 39, 28]]; stream<byte[], io:Error?> byteStream = content.toStream(); io:Error? result = io:fileWriteBlocksFromStream("./resources/myfile.txt", byteStream);
Parameters
- path string - The path of the file
- option FileWriteOption (default OVERWRITE) - To indicate whether to overwrite or append the given content
Return Type
- Error? - An
io:Error
or else()
fileWriteBytes
function fileWriteBytes(string path, byte[] content, FileWriteOption option) returns Error?
Write a set of bytes to a file.
byte[] content = [60, 78, 39, 28]; io:Error? result = io:fileWriteBytes("./resources/myfile.txt", content);
Parameters
- path string - The path of the file
- content byte[] - Byte content to write
- option FileWriteOption (default OVERWRITE) - To indicate whether to overwrite or append the given content
Return Type
- Error? - An
io:Error
or else()
fileWriteCsv
function fileWriteCsv(string path, string[]|map<anydata>[] content, FileWriteOption option) returns Error?
Write CSV content to a file.
When the input is a record[] type in OVERWRITE
, headers will be written to the CSV file by default.
For APPEND
, order of the existing csv file is inferred using the headers and used as the order.
type Coord record {int x;int y;}; Coord[] contentRecord = [{x: 1,y: 2},{x: 1,y: 2}] string[][] content = [["Anne", "Johnson", "SE"], ["John", "Cameron", "QA"]]; io:Error? result = io:fileWriteCsv("./resources/myfile.csv", content); io:Error? resultRecord = io:fileWriteCsv("./resources/myfileRecord.csv", contentRecord);
Parameters
- path string - The CSV file path
- option FileWriteOption (default OVERWRITE) - To indicate whether to overwrite or append the given content
Return Type
- Error? -
()
when the writing was successful or anio:Error
fileWriteCsvFromStream
function fileWriteCsvFromStream(string path, stream<string[]|map<anydata>, Error?> content, FileWriteOption option) returns Error?
Write CSV record stream to a file.
When the input is a stream<record, io:Error?>
in OVERWRITE
, headers will be written to the CSV file by default.
For APPEND
, order of the existing csv file is inferred using the headers and used as the order.
type Coord record {int x;int y;}; Coord[] contentRecord = [{x: 1,y: 2},{x: 1,y: 2}] string[][] content = [["Anne", "Johnson", "SE"], ["John", "Cameron", "QA"]]; stream<string[], io:Error?> stringStream = content.toStream(); stream<Coord, io:Error?> recordStream = contentRecord.toStream(); io:Error? result = io:fileWriteCsvFromStream("./resources/myfile.csv", stringStream); io:Error? resultRecord = io:fileWriteCsvFromStream("./resources/myfileRecord.csv", recordStream);
Parameters
- path string - The CSV file path
- option FileWriteOption (default OVERWRITE) - To indicate whether to overwrite or append the given content
Return Type
- Error? -
()
when the writing was successful or anio:Error
fileWriteJson
Write a JSON to a file.
json content = {"name": "Anne", "age": 30}; io:Error? result = io:fileWriteJson("./resources/myfile.json", content);
Return Type
- Error? -
()
when the writing was successful or anio:Error
fileWriteLines
function fileWriteLines(string path, string[] content, FileWriteOption option) returns Error?
Write an array of lines to a file.
During the writing operation, a newline character \n
will be added after each line.
string[] content = ["Hello Universe..!!", "How are you?"]; io:Error? result = io:fileWriteLines("./resources/myfile.txt", content);
Parameters
- path string - The path of the file
- content string[] - An array of string lines to write
- option FileWriteOption (default OVERWRITE) - To indicate whether to overwrite or append the given content
Return Type
- Error? -
()
when the writing was successful or anio:Error
fileWriteLinesFromStream
function fileWriteLinesFromStream(string path, stream<string, Error?> lineStream, FileWriteOption option) returns Error?
Write stream of lines to a file.
During the writing operation, a newline character \n
will be added after each line.
string content = ["Hello Universe..!!", "How are you?"]; stream<string, io:Error?> lineStream = content.toStream(); io:Error? result = io:fileWriteLinesFromStream("./resources/myfile.txt", lineStream);
Parameters
- path string - The path of the file
- option FileWriteOption (default OVERWRITE) - To indicate whether to overwrite or append the given content
Return Type
- Error? -
()
when the writing was successful or anio:Error
fileWriteString
function fileWriteString(string path, string content, FileWriteOption option) returns Error?
Write a string content to a file.
string content = "Hello Universe..!!"; io:Error? result = io:fileWriteString("./resources/myfile.txt", content);
Parameters
- path string - The path of the file
- content string - String content to write
- option FileWriteOption (default OVERWRITE) - To indicate whether to overwrite or append the given content
Return Type
- Error? -
()
when the writing was successful or anio:Error
fileWriteXml
function fileWriteXml(string path, xml content, FileWriteOption fileWriteOption, *XmlWriteOptions xmlOptions) returns Error?
Write XML content to a file.
xml content = xml `<book>The Lost World</book>`; io:Error? result = io:fileWriteXml("./resources/myfile.xml", content);
Parameters
- path string - The path of the XML file
- content xml - XML content to write
- fileWriteOption FileWriteOption (default OVERWRITE) - File write option (
OVERWRITE
andAPPEND
are the possible values and the default value isOVERWRITE
)
- xmlOptions *XmlWriteOptions - XML writing options (XML entity type and DOCTYPE)
Return Type
- Error? -
()
value when the writing was successful or anio:Error
fprint
function fprint(FileOutputStream fileOutputStream, Printable... values)
Prints any
, error
, or string templates(such as The respective int value is ${val}
) value(s) to
a given stream(STDOUT or STDERR).
io:fprint(io:stderr, "Unexpected error occurred");
Parameters
- fileOutputStream FileOutputStream - The output stream (
io:stdout
orio:stderr
) content needs to be printed
- values Printable... - The value(s) to be printed
fprintln
function fprintln(FileOutputStream fileOutputStream, Printable... values)
Prints any
, error
, or string templates(such as The respective int value is ${val}
) value(s) to
a given stream(STDOUT or STDERR) followed by a new line.
io:fprintln(io:stderr, "Unexpected error occurred");
Parameters
- fileOutputStream FileOutputStream - The output stream (
io:stdout
orio:stderr
) content needs to be printed
- values Printable... - The value(s) to be printed
openReadableCsvFile
function openReadableCsvFile(string path, Separator fieldSeparator, string charset, int skipHeaders) returns ReadableCSVChannel|Error
Retrieves a readable CSV channel from a given file path.
io:ReadableCSVChannel rCsvChannel = check io:openReadableCsvFile(srcFileName);
Parameters
- path string - File path, which describes the location of the CSV
- fieldSeparator Separator (default ",") - CSV record separator (i.e., comma or tab)
- charset string (default "UTF-8") - Representation of the encoding characters in the file
- skipHeaders int (default 0) - Number of headers, which should be skipped
Return Type
- ReadableCSVChannel|Error - The
io:ReadableCSVChannel
, which could be used to iterate through the CSV records or else anio:Error
if any error occurred
openReadableFile
function openReadableFile(string path) returns ReadableByteChannel|Error
Retrieves a ReadableByteChannel
from a given file path.
io:ReadableByteChannel readableFieldResult = check io:openReadableFile("./files/sample.txt");
Parameters
- path string - Relative/absolute path string to locate the file
Return Type
- ReadableByteChannel|Error - The
io:ReadableByteChannel
related to the given file or else anio:Error
if there is an error while opening
openWritableCsvFile
function openWritableCsvFile(string path, Separator fieldSeparator, string charset, int skipHeaders, FileWriteOption option) returns WritableCSVChannel|Error
Retrieves a writable CSV channel from a given file path.
io:WritableCSVChannel wCsvChannel = check io:openWritableCsvFile(srcFileName);
Parameters
- path string - File path, which describes the location of the CSV
- fieldSeparator Separator (default ",") - CSV record separator (i.e., comma or tab)
- charset string (default "UTF-8") - Representation of the encoding characters in the file
- skipHeaders int (default 0) - Number of headers, which should be skipped
- option FileWriteOption (default OVERWRITE) - To indicate whether to overwrite or append the given content
Return Type
- WritableCSVChannel|Error - The
io:WritableCSVChannel
, which could be used to write the CSV records or else anio:Error
if any error occurred
openWritableFile
function openWritableFile(string path, FileWriteOption option) returns WritableByteChannel|Error
Retrieves a WritableByteChannel
from a given file path.
io:WritableByteChannel writableFileResult = check io:openWritableFile("./files/sampleResponse.txt");
Parameters
- path string - Relative/absolute path string to locate the file
- option FileWriteOption (default OVERWRITE) - To indicate whether to overwrite or append the given content
Return Type
- WritableByteChannel|Error - The
io:WritableByteChannel
related to the given file or else anio:Error
if any error occurred
function print(Printable... values)
Prints any
, error
, or string templates (such as The respective int value is ${val}
) value(s) to the STDOUT
.
io:print("Start processing the CSV file from ", srcFileName);
Parameters
- values Printable... - The value(s) to be printed
println
function println(Printable... values)
Prints any
, error
or string templates(such as The respective int value is ${val}
) value(s) to the STDOUT
followed by a new line.
io:println("Start processing the CSV file from ", srcFileName);
Parameters
- values Printable... - The value(s) to be printed
readln
function readln(any? a) returns string
Retrieves the input read from the STDIN.
string choice = io:readln("Enter choice 1 - 5: "); string choice = io:readln();
Parameters
- a any? (default ()) - Any value to be printed
Return Type
- string - Input read from the STDIN
Classes
io: BlockStream
The BlockStream
is used to initialize a stream of type Block
. This BlockStream
refers to the stream that is embedded to
the I/O byte channels.
Constructor
Initialize a BlockStream
using an io:ReadableByteChannel
.
init (ReadableByteChannel readableByteChannel, int blockSize)
- readableByteChannel ReadableByteChannel - The
io:ReadableByteChannel
that this block stream is referred to
- blockSize int - The size of a block as an integer
next
The next function reads and returns the next block of the related stream.
Return Type
close
function close() returns Error?
Closes the stream. The primary usage of this function is to close the stream without reaching the end
If the stream reaches the end, the BlockStream.next()
will automatically close the stream.
Return Type
- Error? -
()
when the closing was successful or anio:Error
io: CsvIterator
The iterator for the stream returned in readFileCsvAsStream
function.
next
function next() returns record {| value anydata |}|error?
close
function close() returns Error?
io: CSVStream
The io:CSVStream
is used to initialize a stream of type CSV records. This io:CSVStream
refers to the stream
that is embedded to the I/O record channels.
Constructor
Initialize a CSVStream
using an io:ReadableTextRecordChannel
.
init (ReadableTextRecordChannel readableTextRecordChannel)
- readableTextRecordChannel ReadableTextRecordChannel - The
io:ReadableTextRecordChannel
that this CSV stream is referred to
next
The next function reads and returns the next CSV record of the related stream.
Return Type
close
function close() returns Error?
Close the stream. The primary usage of this function is to close the stream without reaching the end.
If the stream reaches the end, the CSVStream.next()
will automatically close the stream.
Return Type
- Error? -
()
when the closing was successful or anio:Error
io: LineStream
The io:LineStream
is used to initialize a stream of the type strings(lines). This io:LineStream
refers to the
stream that is embedded to the I/O character channels.
Constructor
Initialize an io:LineStream
using an io:ReadableCharacterChannel
.
init (ReadableCharacterChannel readableCharacterChannel)
- readableCharacterChannel ReadableCharacterChannel - The
io:ReadableCharacterChannel
that the line stream is referred to
next
The next function reads and returns the next line of the related stream.
Return Type
close
function close() returns Error?
Closes the stream. The primary usage of this function is to close the stream without reaching the end
If the stream reaches the end, the LineStream.next()
will automatically close the stream.
Return Type
- Error? -
()
when the closing was successful or anio:Error
io: ReadableByteChannel
ReadableByteChannel represents an input resource (i.e file), which could be used to source bytes.
A file path or an in-memory byte
array can be used to obtain an io:ReadableByteChannel
.
An io:ReadableByteChannel
does not support initialization, and it should be obtained using the following methods or implemented natively.
io:openReadableFile("./files/sample.txt")
- used to obtain an io:ReadableByteChannel
from a given file path
io:createReadableChannel(byteArray)
- used to obtain an io:ReadableByteChannel
from a given byte
array
read
Source bytes from a given input resource.
This operation will be asynchronous in which the total number of required bytes might not be returned at a given
time. An io:EofError
will return once the channel reaches the end.
byte[]|io:Error result = readableByteChannel.read(1000);
Parameters
- nBytes int - A positive integer. Represents the number of bytes, which should be read
Return Type
- byte[]|Error - Content (the number of bytes) read, an
EofError
once the channel reaches the end or else anio:Error
readAll
function readAll() returns readonly & byte[]|Error
Read all content of the channel as a byte
array and return a read only byte
array.
byte[]|io:Error result = readableByteChannel.readAll();
Return Type
- readonly & byte[]|Error - A read-only
byte
array or else anio:Error
blockStream
Return a block stream that can be used to read all byte
blocks as a stream.
stream<io:Block, io:Error>|io:Error result = readableByteChannel.blockStream();
Parameters
- blockSize int - A positive integer. Size of the block.
base64Encode
function base64Encode() returns ReadableByteChannel|Error
Encodes a given io:ReadableByteChannel
using the Base64 encoding scheme.
io:ReadableByteChannel|Error encodedChannel = readableByteChannel.base64Encode();
Return Type
- ReadableByteChannel|Error - An encoded
io:ReadableByteChannel
or else anio:Error
base64Decode
function base64Decode() returns ReadableByteChannel|Error
Decodes a given Base64 encoded io:ReadableByteChannel
.
io:ReadableByteChannel|Error encodedChannel = readableByteChannel.base64Decode();
Return Type
- ReadableByteChannel|Error - A decoded
io:ReadableByteChannel
or else anio:Error
close
function close() returns Error?
Closes the io:ReadableByteChannel
.
After a channel is closed, any further reading operations will cause an error.
io:Error? err = readableByteChannel.close();
Return Type
- Error? -
()
or else anio:Error
if any error occurred
io: ReadableCharacterChannel
Represents a channel, which could be used to read characters through a given ReadableByteChannel.
Constructor
Constructs an io:ReadableCharacterChannel
from a given io:ReadableByteChannel
and Charset
.
init (ReadableByteChannel byteChannel, string charset)
- byteChannel ReadableByteChannel - The
io:ReadableByteChannel
, which would be used to read the characters
- charset string - The character set, which is used to encode/decode the given bytes to characters
read
Reads a given number of characters. This will attempt to read up to the numberOfChars
characters of the channel.
An io:EofError
will return once the channel reaches the end.
string|io:Error result = readableCharChannel.read(1000);
Parameters
- numberOfChars int - Number of characters, which should be read
Return Type
readString
Read the entire channel content as a string.
string|io:Error content = readableCharChannel.readString();
readAllLines
Read the entire channel content as a list of lines.
string[]|io:Error content = readableCharChannel.readAllLines();
Return Type
readJson
function readJson() returns json|Error
Reads a JSON from the given channel.
json|io:Error result = readableCharChannel.readJson();
Return Type
- json|Error - The content that is read as a JSON or else an
io:Error
readXml
Reads an XML from the given channel.
json|io:Error result = readableCharChannel.readXml();
readProperty
Reads a property from a .properties file with a default value.
string|io:Error result = readableCharChannel.readProperty(key, defaultValue);
Parameters
- key string - The property key, which needs to be read
- defaultValue string (default "") - The default value to be returned
lineStream
Return a stream of lines that can be used to read all the lines in a file as a stream.
stream<string, io:Error>|io:Error? result = readableCharChannel.lineStream();
readAllProperties
Reads all properties from a .properties file.
map<string>|io:Error result = readableCharChannel.readAllProperties();
close
function close() returns Error?
Closes the character channel. After a channel is closed, any further reading operations will cause an error.
io:Error? err = readableCharChannel.close();
Return Type
- Error? -
()
or else anio:Error
if any error occurred
io: ReadableCSVChannel
Represents a ReadableCSVChannel which could be used to read records from CSV file.
Constructor
Constructs a CSV channel from a CharacterChannel to read CSV records.
init (ReadableCharacterChannel byteChannel, Separator fs, int nHeaders)
- byteChannel ReadableCharacterChannel - The CharacterChannel, which will represent the content in the CSV file
- fs Separator "," - Field separator, which will separate between the records in the CSV file
- nHeaders int 0 - Number of headers, which should be skipped prior to reading records
skipHeaders
function skipHeaders(int nHeaders)
Skips the given number of headers.
readableCSVChannel.skipHeaders(5);
Parameters
- nHeaders int - The number of headers, which should be skipped
hasNext
function hasNext() returns boolean
Indicates whether there's another record, which could be read.
boolean hasNext = readableCSVChannel.hasNext();
Return Type
- boolean - True if there is a record
getNext
Gets the next record from the CSV file.
string[]|io:Error? record = readableCSVChannel.getNext();
csvStream
Returns a CSV record stream that can be used to CSV records as a stream.
stream<string[], io:Error>|io:Error? record = readableCSVChannel.csvStream();
close
function close() returns Error?
Closes the io:ReadableCSVChannel
.
After a channel is closed, any further reading operations will cause an error.
io:Error? err = readableCSVChannel.close();
Return Type
- Error? - An
io:Error
if any error occurred
getTable
function getTable(typedesc<record {}> structType, string[] fieldNames) returns table<record {}>|Error
Returns a table, which corresponds to the CSV records.
var tblResult1 = readableCSVChannel.getTable(Employee); var tblResult2 = readableCSVChannel.getTable(Employee, ["id", "name"]);
Parameters
- structType typedesc<record {}> - The object in which the CSV records should be deserialized
- fieldNames string[] (default []) - The names of the fields used as the (composite) key of the table
Deprecated
This function is deprecated due to the introduction of ReadableCSVChannel.toTable()
, making 'fieldNames' a mandatory parameter
toTable
function toTable(typedesc<record {}> structType, string[] keyFieldNames) returns table<record {}>|Error
Returns a table, which corresponds to the CSV records.
var tblResult = readableCSVChannel.toTable(Employee, ["id", "name"]);
Parameters
- structType typedesc<record {}> - The object in which the CSV records should be deserialized
- keyFieldNames string[] - The names of the fields used as the (composite) key of the table
io: ReadableDataChannel
Represents a data channel for reading data.
Constructor
Initializes the data channel.
init (ReadableByteChannel byteChannel, ByteOrder bOrder)
- byteChannel ReadableByteChannel - The channel, which would represent the source to read/write data
- bOrder ByteOrder "BE" - Network byte order
readInt16
Reads a 16 bit integer.
int|io:Error result = dataChannel.readInt16();
Return Type
readInt32
Reads a 32 bit integer.
int|io:Error result = dataChannel.readInt32();
Return Type
readInt64
Reads a 64 bit integer.
int|io:Error result = dataChannel.readInt64();
Return Type
readFloat32
Reads a 32 bit float.
float|io:Error result = dataChannel.readFloat32();
Return Type
readFloat64
Reads a 64 bit float.
float|io:Error result = dataChannel.readFloat64();
Return Type
readBool
Reads a byte and convert its value to boolean.
boolean|io:Error result = dataChannel.readBool();
readString
Reads the string value represented through the provided number of bytes.
string|io:Error string = dataChannel.readString(10, "UTF-8");
Parameters
- nBytes int - Specifies the number of bytes, which represents the string
- encoding string - Specifies the char-set encoding of the string
readVarInt
Reads a variable length integer.
int|io:Error result = dataChannel.readVarInt();
Return Type
close
function close() returns Error?
Closes the data channel. After a channel is closed, any further reading operations will cause an error.
io:Error? err = dataChannel.close();
Return Type
- Error? -
()
or else anio:Error
if any error occurred
io: ReadableTextRecordChannel
Represents a channel which will allow to read.
Constructor
Constructs a ReadableTextRecordChannel from a given ReadableCharacterChannel.
init (ReadableCharacterChannel charChannel, string fs, string rs, string fmt)
- charChannel ReadableCharacterChannel - CharacterChannel which will point to the input/output resource
- fs string "" - Field separator (this could be a regex)
- rs string "" - Record separator (this could be a regex)
- fmt string "default" -
hasNext
function hasNext() returns boolean
Checks whether there is a record left to be read.
boolean hasNext = readableRecChannel.hasNext();
Return Type
- boolean - True if there is a record left to be read
getNext
Get the next record from the input/output resource.
string[]|io:Error record = readableRecChannel.getNext();
close
function close() returns Error?
Closes the record channel. After a channel is closed, any further reading operations will cause an error.
io:Error err = readableRecChannel.close();
Return Type
- Error? -
()
or else anio:Error
if any error occurred
io: StringReader
Represents a reader which will wrap string content as a channel.
readJson
function readJson() returns json|Error
Reads string as JSON using the reader.
io:StringReader reader = new("{\"name\": \"Alice\"}"); json|io:Error? person = reader.readJson();
Return Type
- json|Error - JSON or else an
io:Error
if any error occurred
readXml
Reads a string as XML using the reader.
io:StringReader reader = new("<Person><Name>Alice</Name></Person>"); xml|io:Error? person = reader.readXml();
readChar
Reads the characters from the given string.
io:StringReader reader = new("Some text"); string|io:Error? person = reader.readChar(4);
Parameters
- nCharacters int - Number of characters to be read
close
function close() returns Error?
Closes the string reader.
io:Error? err = reader.close();
Return Type
- Error? -
()
or else anio:Error
if any error occurred
io: WritableByteChannel
WritableByteChannel represents an output resource (i.e file) which could be used to sink bytes
A file path can be used to obtain an io:WritableByteChannel
.
An io:WritableByteChannel
can only be obtained using the following method or by providing a native implementation.
It cannot be instantiated.
io:openWritableFile("./files/sample.txt")
- used to obtain an io:WritableByteChannel
from a given file path
write
Sinks bytes from a given input/output resource.
This is an asynchronous operation. The method might return before writing all the content.
int|io:Error result = writableByteChannel.write(record, 0);
Parameters
- content byte[] - Block of bytes to be written
- offset int - Offset of the provided content, which needs to be kept when writing bytes
close
function close() returns Error?
Closes the byte channel. After a channel is closed, any further writing operations will cause an error.
io:Error err = writableByteChannel.close();
Return Type
- Error? -
()
or else anio:Error
if any error occurred
io: WritableCharacterChannel
Represents a channel which could be used to write characters through a given WritableCharacterChannel.
Constructor
Constructs an io:WritableByteChannel
from a given io:WritableByteChannel
and Charset
.
init (WritableByteChannel bChannel, string charset)
- bChannel WritableByteChannel - The
io:WritableByteChannel
, which would be used to write the characters
- charset string - The character set, which would be used to encode the given bytes to characters
write
Writes a given sequence of characters (string).
int|io:Error result = writableCharChannel.write("Content", 0);
Parameters
- content string - Content to be written
- startOffset int - Number of characters to be offset when writing the content
writeLine
Writes a string as a line with a following newline character \n
.
io:Error? result = writableCharChannel.writeLine("Content");
Parameters
- content string - Content to be written
Return Type
- Error? -
()
if the writing was successful or anio:Error
writeJson
function writeJson(json content) returns Error?
Writes a given JSON to the given channel.
io:Error? err = writableCharChannel.writeJson(inputJson, 0);
Parameters
- content json - The JSON to be written
Return Type
- Error? -
()
if the writing was successful or anio:Error
writeXml
function writeXml(xml content, XmlDoctype? xmlDoctype) returns Error?
Writes a given XML to the channel.
io:Error? err = writableCharChannel.writeXml(inputXml, 0);
Parameters
- content xml - The XML to be written
- xmlDoctype XmlDoctype? (default ()) - Optional argument to specify the XML DOCTYPE configurations
Return Type
- Error? -
()
or else anio:Error
if any error occurred
writeProperties
Writes a given key-valued pair map<string>
to a property file.
io:Error? err = writableCharChannel.writeProperties(properties);
Parameters
- comment string - Comment describing the property list
Return Type
- Error? -
()
or else anio:Error
if any error occurred
close
function close() returns Error?
Closes the io:WritableCharacterChannel
.
After a channel is closed, any further writing operations will cause an error.
io:Error err = writableCharChannel.close();
Return Type
- Error? -
()
or else anio:Error
if any error occurred
io: WritableCSVChannel
Represents a WritableCSVChannel, which could be used to write records from the CSV file.
Constructor
Constructs a CSV channel from a CharacterChannel
to read/write CSV records.
init (WritableCharacterChannel characterChannel, Separator fs)
- characterChannel WritableCharacterChannel -
- fs Separator "," - Field separator, which will separate the records in the CSV
write
Writes the record to a given CSV file.
io:Error err = csvChannel.write(record);
Parameters
- csvRecord string[] - A record to be written to the channel
Return Type
- Error? - An
io:Error
if the record could not be written properly
close
function close() returns Error?
Closes the io:WritableCSVChannel
.
After a channel is closed, any further writing operations will cause an error.
io:Error? err = csvChannel.close();
Return Type
- Error? -
()
or else anio:Error
if any error occurred
io: WritableDataChannel
Represents a WritableDataChannel for writing data.
Constructor
Initializes data channel.
init (WritableByteChannel byteChannel, ByteOrder bOrder)
- byteChannel WritableByteChannel - Channel, which would represent the source to read/write data
- bOrder ByteOrder "BE" - Network byte order
writeInt16
Writes a 16 bit integer.
io:Error? err = dataChannel.writeInt16(length);
Parameters
- value int - The integer, which will be written
Return Type
- Error? -
()
if the content is written successfully or else anio:Error
if any error occurred
writeInt32
Writes a 32 bit integer.
io:Error? err = dataChannel.writeInt32(length);
Parameters
- value int - The integer, which will be written
Return Type
- Error? -
()
if the content is written successfully or else anio:Error
if any error occurred
writeInt64
Writes a 64 bit integer.
io:Error? err = dataChannel.writeInt64(length);
Parameters
- value int - The integer, which will be written
Return Type
- Error? -
()
if the content is written successfully or else anio:Error
if any error occurred
writeFloat32
Writes a 32 bit float.
io:Error? err = dataChannel.writeFloat32(3.12);
Parameters
- value float - The float, which will be written
Return Type
- Error? -
()
if the float is written successfully or else anio:Error
if any error occurred
writeFloat64
Writes a 64 bit float.
io:Error? err = dataChannel.writeFloat32(3.12);
Parameters
- value float - The float, which will be written
Return Type
- Error? -
()
if the float is written successfully or else anio:Error
if any error occurred
writeBool
Writes a boolean.
io:Error? err = dataChannel.writeInt64(length);
Parameters
- value boolean - The boolean, which will be written
Return Type
- Error? -
()
if the content is written successfully or else anio:Error
if any error occurred
writeString
Writes a given string value to the respective channel.
io:Error? err = dataChannel.writeString(record);
Parameters
- value string - The value, which should be written
- encoding string - The encoding, which will represent the value string
Return Type
- Error? -
()
if the content is written successfully or else anio:Error
if any error occurred
writeVarInt
Writes a variable-length integer.
io:Error? err = dataChannel.writeVarInt(length);
Parameters
- value int - The int, which will be written
Return Type
- Error? - The value of the integer, which is written or else an
io:Error
if any error occurred
close
function close() returns Error?
Closes the data channel. After a channel is closed, any further writing operations will cause an error.
io:Error? err = dataChannel.close();
Return Type
- Error? -
()
if the channel is closed successfully or else anio:Error
if any error occurred
io: WritableTextRecordChannel
Represents a channel, which will allow to write records through a given WritableCharacterChannel.
Constructor
Constructs a DelimitedTextRecordChannel from a given WritableCharacterChannel.
init (WritableCharacterChannel characterChannel, string fs, string rs, string fmt)
- characterChannel WritableCharacterChannel - The
io:WritableCharacterChannel
, which will point to the input/output resource
- fs string "" - Field separator (this could be a regex)
- rs string "" - Record separator (this could be a regex)
- fmt string "default" - The format, which will be used to represent the CSV (this could be "DEFAULT" (the format specified by the CSVChannel), "CSV" (Field separator would be "," and record separator would be a new line) or else "TDF" (Field separator will be a tab and record separator will be a new line)
write
Writes records to a given output resource.
io:Error? err = writableChannel.write(records);
Parameters
- textRecord string[] - List of fields to be written
Return Type
- Error? - An
io:Error
if the records could not be written properly or else()
close
function close() returns Error?
Closes the record channel. After a channel is closed, any further writing operations will cause an error.
io:Error? err = writableChannel.close();
Return Type
- Error? - An
io:Error
if the record channel could not be closed properly or else()
Constants
io: BIG_ENDIAN
Specifies the bytes to be in the order of most significant byte first.
io: COLON
Colon (:) will be use as the field separator.
io: COMMA
Comma (,) will be used as the field separator.
io: CSV
Field separator will be "," and the record separator will be a new line.
io: CSV_RECORD_SEPARATOR
Represents the record separator of the CSV file.
io: DEFAULT
The default value is the format specified by the CSVChannel. Precedence will be given to the field separator and record separator.
io: DEFAULT_ENCODING
Default encoding for the abstract read/write APIs.
io: FS_COLON
Represents the colon separator, which should be used to identify colon-separated files.
io: LITTLE_ENDIAN
Specifies the byte order to be the least significant byte first.
io: MINIMUM_HEADER_COUNT
Represents the minimum number of headers, which will be included in the CSV.
io: NEW_LINE
New line character.
io: stderr
Represents the standard error stream.
io: stdout
Represents the standard output stream.
io: TAB
Tab (/t) will be use as the field separator.
io: TDF
Field separator will be a tab and the record separator will be a new line.
Enums
io: FileWriteOption
Represents a file opening options for writing.
Members
io: XmlEntityType
Represents the XML entity type that needs to be written.
Members
Records
io: XmlDoctype
Represents the XML DOCTYPE entity.
Fields
- system string?(default ()) - The system identifier
- 'public string?(default ()) -
- internalSubset string?(default ()) - Internal DTD schema
io: XmlWriteOptions
The writing options of an XML.
Fields
- xmlEntityType XmlEntityType(default DOCUMENT_ENTITY) - The entity type of the XML input (the default value is
DOCUMENT_ENTITY
)
- doctype XmlDoctype?(default ()) - XML DOCTYPE value (the default value is
()
)
Errors
io: AccessDeniedError
This will get returned due to file permission issues.
io: ConfigurationError
This will get returned if there is an invalid configuration.
io: ConnectionTimedOutError
This will return when connection timed out happen when try to connect to a remote host.
io: EofError
This will get returned if read operations are performed on a channel after it closed.
io: Error
Represents IO module related errors.
io: FileNotFoundError
This will get returned if the file is not available in the given file path.
io: GenericError
Represents generic IO error. The detail record contains the information related to the error.
io: TypeMismatchError
This will get returned when there is an mismatch of given type and the expected type.
Object types
io: PrintableRawTemplate
Represents raw templates.
e.g: The respective int value is ${val}
Fields
- strings string[] & readonly - String values of the template as an array
- insertions Printable[] - Parameterized values/expressions after evaluations as an array
Union types
io: Printable
Printable
Defines all the printable types.
- any typed value
- errors
io:PrintableRawTemplate
- an raw templated value
io: FileOutputStream
FileOutputStream
Defines the output streaming types.
stdout
- standard output streamstderr
- standard error stream
io: ByteOrder
ByteOrder
Represents network byte order.
BIG_ENDIAN - specifies the bytes to be in the order of most significant byte first.
LITTLE_ENDIAN - specifies the byte order to be the least significant byte first.
io: Format
Format
The format, which will be used to represent the CSV.
DEFAULT - The default value is the format specified by the CSVChannel. Precedence will be given to the field separator and record separator.
CSV - Field separator will be "," and the record separator will be a new line.
TDF - Field separator will be a tab and the record separator will be a new line.
io: Separator
Separator
Field separators, which are supported by the DelimitedTextRecordChannel
.
COMMA - Delimited text records will be separated using a comma
TAB - Delimited text records will be separated using a tab
COLON - Delimited text records will be separated using a colon(:)
Intersection types
io: Block
Block
The read-only byte array that is used to read the byte content from the streams.
Import
import ballerina/io;
Metadata
Released date: 18 days ago
Version: 1.6.3
License: Apache-2.0
Compatibility
Platform: java17
Ballerina version: 2201.8.0
GraalVM compatible: Yes
Pull count
Total: 654957
Current verison: 8948
Weekly downloads
Keywords
io
json
xml
csv
file
Contributors