ballerina/io package
Package Overview
This package is designed to support input and output operations via channels in a canonical way, either in a blocking, or non-blocking manner.
Channels
A channel represents an I/O source or sink of some bytes, characters, or records that are opened for reading, or writing, respectively.
Byte channels
The most primitive channel is the ByteChannel
which reads and writes 8-bit bytes.
// Open a file in read-write mode.
io:ByteChannel byteChannel = io:openFile("some/file.txt", io:RW);
// Here is how 100 bytes are read from the channel.
var readResult = byteChannel.read(100);
match readResult {
(blob, int) content => {
return content; // Return the read content.
}
error err => {
return err; // An IO error occurred when reading the bytes.
}
}
// Write some content to the beginning of the file.
blob content = "some content".toBlob("UTF-8");
var writeResult = byteChannel.write(content, 0);
match writeResult {
int numberOfBytesWritten => {
return numberOfBytesWritten; // Return the count of written bytes.
}
error err => {
return err; // An IO error occurred when writing the bytes.
}
}
Character channels
The CharacterChannel
is used to read and write characters. The charset encoding is specified when creating the
CharacterChannel
.
// Create a `CharacterChannel` from the `ByteChannel`.
var charChannel = new io:CharacterChannel(byteChannel, "UTF-8");
If a CharacterChannel
points to a JSON or XML source, it can be read and then written, directly into a variable of
the respective type.
// Reading a JSON.
var readResult = charChannel.readJson();
match readResult {
json value => {
return value; // Return the read JSON value.;
}
error err => {
return err; // An IO error occurred when reading the JSON.
}
}
// Writing a JSON.
json content = {fname:"Jhon", lname:"Doe", age:40};
var writeResult = charChannel.writeJson(content);
match writeResult {
error err => {
return err; // An IO error occurred when writing the JSON.
}
() => {
io:println("JSON content written successfully.");
}
}
// Reading an XML.
var result = charChannel.readXml();
Record channels
Ballerina also supports I/O for delimited records.
// Creating a `DelimitedRecordChannel` from the `CharacterChannel`.
// Records are separated using a new line, and
// fields of a record are separated using a comma.
var recordsChannel = new io:DelimitedTextRecordChannel(charChannel, fs = ",", rs = "\n");
// Reading a few records.
while (recordsChannel.hasNext()) {
var result = recordsChannel.getNext();
match result {
string[] record => {
println(record); // Retrieved a record.
}
error err => {
return err; // An IO error occurred when reading the records.
}
() => {
error e = {message: "Record channel not initialized properly."};
return e;
}
}
}
A .CSV
file can be read and written directly into a CSVChannel
, as shown in this code snippet.
var csvChannel = check io:openCsvFile("records.csv");
Records of the .CSV
file can read directly into a table of a matching type.
// First let’s define a type that matches a record in the CSV file.
type Employee {
string id;
string name;
float salary;
};
// Now read the CSV file as a table of Employees and compute total salary.
float totalSalary = 0;
match csvChannel.getTable(Employee) {
table<Employee> employees => {
foreach employee in employees {
totalSalary += employee.salary;
}
return total; // Return total of salaries of all employees.
}
error err => {
return err; // An IO error occurred when reading the records.
}
}
Package contents
Type Definitions
Type | Values | Description | |
---|---|---|---|
Format | tdf | default | csv | Format which will be used to represent the CSV.
|
|
Mode | w | rw | r | a | Represents the set of permissions supported to open file. READ - open the file in read mode WRITE - open the file in write mode READ/WRITE - open the file either to read or write APPEND - append to existing file instead of replacing |
|
Separator | : | , | | Field separators which are supported by DelimitedTextRecordChannel. |
Records Summary
Record | Description | ||
---|---|---|---|
SocketProperties | SocketProperties represents the properties which are used to configure TCP connection. |
Objects Summary
Object | Description | ||
---|---|---|---|
ByteChannel | ByteChannel represents an input/output resource (i.e file, socket). which could be used to source/sink bytes. |
||
CSVChannel | Represents a CSVChannel which could be used to read/write records from CSV file. |
||
CharacterChannel | Represents a channel which could be used to read/write characters through a given ByteChannel. |
||
DelimitedTextRecordChannel | Represents a channel which will allow to read/write records through a given CharacterChannel. |
||
Socket | Represents a TCP socket. |
Functions Summary
Return Type | Function and Description | ||
---|---|---|---|
CSVChannel | openCsvFile(string path) Retrieves a CSV channel from a give file path. |
||
ByteChannel | openFile(string path, Mode accessMode) Retrieves a ByteChannel from a given file path. |
||
Socket | error | openSecureSocket(string host, int port, SocketProperties options) Opens a secure socket connection with a remote server. |
||
Socket | error | openSocket(string host, int port, SocketProperties options) Opens a socket from a specified network location. |
||
print() Prints 'any' value to the STDOUT. |
|||
println() Prints an any value to the STDOUT in a new line. |
|||
string | readln(any a) Returns the input read from STDIN. |
||
string | sprintf(string format) Returns a formatted string using the specified format string and arguments. |
Global Variables
Name | Data Type | Description | |
---|---|---|---|
APPEND | Mode | ||
COLON | Separator | ||
COMMA | Separator | ||
CSV | Format | ||
DEFAULT | Format | ||
READ | Mode | ||
RW | Mode | ||
TAB | Separator | ||
TDF | Format | ||
WRITE | Mode |
public type SocketProperties
SocketProperties represents the properties which are used to configure TCP connection.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
localPort | int | Local port the socket client should bind |
|
keyStoreFile | string | Relative/absolute path to locate keystore file |
|
keyStorePassword | string | Keystore password |
|
trustStoreFile | string | Relative/absolute path to locate truststore file |
|
trustStorePassword | string | Truststore password |
|
certPassword | string | Password of the certificate |
|
sslEnabledProtocols | string | Protocols supported for SSL (i.e TLSv1.2,TLSv1.1,TLSv1) |
|
ciphers | string | Encrypt/decrypt algorithms (i.e RSA, SHA-256) |
|
sslProtocol | string | Supported SSL protocols (i.e SSL, TLS) |
public function openCsvFile(string path) returns (CSVChannel)
Retrieves a CSV channel from a give file path.
Parameter Name | Data Type | Default Value | Description |
---|---|---|---|
path | string | File path which describes the location of the CSV |
Return Type | Description | ||
---|---|---|---|
CSVChannel | CSVChannel which could be used to iterate through the CSV records |
public function openFile(string path, Mode accessMode) returns (ByteChannel)
Retrieves a ByteChannel from a given file path.
Parameter Name | Data Type | Default Value | Description |
---|---|---|---|
path | string | Relative/absolute path string to locate the file |
|
accessMode | Mode | Permission to open the file |
Return Type | Description | ||
---|---|---|---|
ByteChannel | ByteChannel representation of the file resource |
public function openSecureSocket(string host, int port, SocketProperties options) returns (Socket | error)
Opens a secure socket connection with a remote server.
Parameter Name | Data Type | Default Value | Description |
---|---|---|---|
host | string | Remote server domain/IP |
|
port | int | Remote server port |
|
options | SocketProperties | Mata data to initialize the connection(i.e security information) |
Return Type | Description | ||
---|---|---|---|
Socket | error | Socket which will represent the network object or an error |
public function openSocket(string host, int port, SocketProperties options) returns (Socket | error)
Opens a socket from a specified network location.
Parameter Name | Data Type | Default Value | Description |
---|---|---|---|
host | string | Remote server domain/IP |
|
port | int | Remote server port |
|
options | SocketProperties | Connection stream that bridge the client and the server |
Return Type | Description | ||
---|---|---|---|
Socket | error | Socket which will allow to communicate with a remote server or error |
public function print()
Prints 'any' value to the STDOUT.
public function println()
Prints an any value to the STDOUT in a new line.
public function readln(any a) returns (string)
Returns the input read from STDIN.
Parameter Name | Data Type | Default Value | Description |
---|---|---|---|
a | any | Any value to be printed |
Return Type | Description | ||
---|---|---|---|
string | Input read from STDIN |
public function sprintf(string format) returns (string)
Returns a formatted string using the specified format string and arguments.
Parameter Name | Data Type | Default Value | Description |
---|---|---|---|
format | string | Represent the format of the string which should be returned |
Return Type | Description | ||
---|---|---|---|
string | Formatted string |
public type ByteChannel object
ByteChannel represents an input/output resource (i.e file, socket). which could be used to source/sink bytes.
-
<ByteChannel> read(int nBytes) returns ((blob,int) | error)
Source bytes from a given input/output resource.
Number of bytes returned will be < 0 if the file reached its end. This operation will be asynchronous, where the total number of required bytes might not be returned at a given time.
Parameter Name Data Type Default Value Description nBytes int Positive integer. Represents the number of bytes which should be read
Return Type Description (blob,int) | error Content, the number of bytes read or an error
-
<ByteChannel> write(blob content, int offset) returns (int | error)
Sink bytes from a given input/output resource.
This operation will be asynchronous, write might return without writing all the content.
Parameter Name Data Type Default Value Description content blob Block of bytes which should be written
offset int Return Type Description int | error Offset which should be kept when writing bytes
-
<ByteChannel> close() returns (error)
Closes a given byte channel.
Return Type Description error Will return () if there's no error
-
<ByteChannel> base64Encode() returns (ByteChannel | error)
Encodes a given ByteChannel with Base64 encoding scheme.
Return Type Description ByteChannel | error Return an encoded ByteChannel or an error
-
<ByteChannel> base64Decode() returns (ByteChannel | error)
Decodes a given ByteChannel with Base64 encoding scheme.
Return Type Description ByteChannel | error Return a decoded ByteChannel or an error
public type CSVChannel object
Represents a CSVChannel which could be used to read/write records from CSV file.
-
<CSVChannel> hasNext() returns (boolean)
Indicates whether there's another record which could be read.
Return Type Description boolean True if there's a record
-
<CSVChannel> getNext() returns (string[] | error)
Gets the next record from the CSV file.
Return Type Description string[] | error List of fields in the CSV or error
-
<CSVChannel> write(string[] record) returns (error)
Writes record to a given CSV file.
Parameter Name Data Type Default Value Description record string[] Return Type Description error Returns an error if the record could not be written properly
-
<CSVChannel> close() returns (error)
Closes a given CSVChannel.
Return Type Description error Returns if an error is encountered
-
<CSVChannel> getTable(typedesc structType) returns (table | error)
Returns a table which coresponds to the CSV records.
Parameter Name Data Type Default Value Description structType typedesc The object the CSV records should be deserialized
Return Type Description table | error Table which represents CSV records or error
public type CharacterChannel object
Represents a channel which could be used to read/write characters through a given ByteChannel.
-
<CharacterChannel> read(int numberOfChars) returns (string | error)
Reads a given number of characters.
Parameter Name Data Type Default Value Description numberOfChars int Number of characters which should be read
Return Type Description string | error Content which is read or an error
-
<CharacterChannel> write(string content, int startOffset) returns (int | error)
Writes a given sequence of characters (string).
Parameter Name Data Type Default Value Description content string Content which should be written
startOffset int Number of characters which should be offset when writing content
Return Type Description int | error -
<CharacterChannel> readJson() returns (json | error)
Reads a json from the given channel.
Return Type Description json | error Read json string or an error
-
<CharacterChannel> readXml() returns (xml | error)
Reads a XML from the given channel.
Return Type Description xml | error Read xml or an error
-
<CharacterChannel> writeJson(json content) returns (error)
Writes a given json to the given channel.
Parameter Name Data Type Default Value Description content json The json which should be written
Return Type Description error If an error occurred while writing
-
<CharacterChannel> writeXml(xml content) returns (error)
Writes a given xml to the channel.
Parameter Name Data Type Default Value Description content xml The XML which should be written
Return Type Description error If an error occurred while writing
-
<CharacterChannel> close() returns (error)
Closes a given character channel.
Return Type Description error If an error occurred while writing
public type DelimitedTextRecordChannel object
Represents a channel which will allow to read/write records through a given CharacterChannel.
-
<DelimitedTextRecordChannel> hasNext() returns (boolean)
Checks whether there's a record left to be read.
Return Type Description boolean True if there's a record left to be read
-
<DelimitedTextRecordChannel> getNext() returns (string[] | error)
Get next record from the input/output resource.
Return Type Description string[] | error Set of fields included in the record or an error
-
<DelimitedTextRecordChannel> write(string[] record) returns (error)
Writes records to a given input/output resource.
Parameter Name Data Type Default Value Description record string[] list of fields which should be written
Return Type Description error An error if the records could not be written properly
-
<DelimitedTextRecordChannel> close() returns (error)
Closes a given record channel.
Return Type Description error An error if the record channel could not be closed properly
public type Socket object
Represents a TCP socket.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
channel | ByteChannel | ByteChannel which will represent the socket connection |
|
port | int | Remote server connection port |
|
localPort | int | Local port the socket connection should bound |
|
address | string | IP/Host of the remote server |
|
localAddress | string | Local interface the connection should bound |
-
<Socket> close() returns (error)
Closes a socket connection.
Return Type Description error An error if the connection could not be closed properly
-
<Socket> shutdownInput() returns (error)
Shutdown the connection from reading. In this case content cannot be read from the server.
Return Type Description error An error if the connection could not be shutdown properly
-
<Socket> shutdownOutput() returns (error)
Shutdown the connection from writing. In this case content cannot be written to the server.
Return Type Description error An error if the connection could not be shutdown properly