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:printio:printlnio: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:fileReadBytesio:fileReadBlocksAsStreamio:fileWriteBytesio: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:fileReadStringio:fileReadLinesio:fileReadLinesAsStreamio:fileWriteLinesio: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:fileReadCsvio:fileReadCsvAsStreamio:fileWriteCsvio:fileWriteCsvFromStream
JSON I/O
The JSON I/O APIs provide the reading and writing APIs for JSON content. Those APIs are:
io:fileReadJsonio:fileWriteJson
XML I/O
The XML I/O APIs provide the reading and writing APIs for XML content. Those APIs are:
io:fileReadXmlio:fileWriteXml
Functions
createReadableChannel
function createReadableChannel(byte[] content) returns ReadableByteChannel|ErrorCreates an in-memory channel, which will be a reference stream of bytes.
var byteChannel = io:createReadableChannel(content);
Parameters
- content byte[] - The content as a byte array, which should be exposed as a channel
Return Type
- ReadableByteChannel|Error - The
io:ReadableByteChannelrelated to the given bytes or else anio:Errorif any error occurred
fileReadBlocksAsStream
Reads the entire file content as a stream of blocks.
stream<io:Block, io:Error?>|io:Error content = io:fileReadBlocksAsStream("./resources/myfile.txt", 1000);
fileReadBytes
Reads the entire file content as a byte array.
byte[]|io:Error content = io:fileReadBytes("./resources/myfile.txt");
Parameters
- path string - The file path
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[]|ErrorReads 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?>|ErrorReads 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 JSON file path
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 file path
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 file path
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 file path
fileReadXml
Reads file content as an XML.
xml|io:Error content = io:fileReadXml("./resources/myfile.xml");
Parameters
- path string - The XML file path
fileWriteBlocksFromStream
function fileWriteBlocksFromStream(string path, stream<byte[], Error?> byteStream, FileWriteOption option) returns Error?Writes 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 file path
- option FileWriteOption (default OVERWRITE) - Indicate whether to overwrite or append the given content
Return Type
- Error? - An
io:Errorif the write operation fails, or ()
fileWriteBytes
function fileWriteBytes(string path, byte[] content, FileWriteOption option) returns Error?Writes 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 file path
- content byte[] - Byte content to write
- option FileWriteOption (default OVERWRITE) - Indicate whether to overwrite or append the given content
Return Type
- Error? - An
io:Errorif the write operation fails, or ()
fileWriteCsv
function fileWriteCsv(string path, string[][]|map<anydata>[] content, FileWriteOption option) returns Error?Writes CSV content to a file.
When the input is a record[] type in OVERWRITE, headers will be written to the CSV file.
For APPEND, order of the existing csv file is inferred using the headers.
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) - 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?Writes 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.
For APPEND, order of the existing csv file is inferred using the headers.
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) - Indicate whether to overwrite or append the given content
Return Type
- Error? -
()when the writing was successful or anio:Error
fileWriteJson
Writes 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?Writes 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 file path
- content string[] - An array of string lines to write
- option FileWriteOption (default OVERWRITE) - 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?Writes a 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 file path
- option FileWriteOption (default OVERWRITE) - 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?Writes a string content to a file.
string content = "Hello Universe..!!"; io:Error? result = io:fileWriteString("./resources/myfile.txt", content);
Parameters
- path string - The file path
- content string - String content to write
- option FileWriteOption (default OVERWRITE) - 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?Writes 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 XML file path
- content xml - XML content to write
- fileWriteOption FileWriteOption (default OVERWRITE) - File write option (
OVERWRITEandAPPENDare 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 value(s) to a given stream(STDOUT or STDERR).
io:fprint(io:stderr, "Unexpected error occurred");
Parameters
- fileOutputStream FileOutputStream - The output stream (
io:stdoutorio: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 value(s) to a given stream(STDOUT or STDERR) and terminates the line.
io:fprintln(io:stderr, "Unexpected error occurred");
Parameters
- fileOutputStream FileOutputStream - The output stream (
io:stdoutorio: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|ErrorRetrieves a readable CSV channel from a given file path.
io:ReadableCSVChannel rCsvChannel = check io:openReadableCsvFile(srcFileName);
Parameters
- path string - The CSV file path
- fieldSeparator Separator (default ",") - CSV record separator (i.e., comma or tab)
- charset string (default "UTF-8") - The character encoding used to read 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:Errorif any error occurred
openReadableFile
function openReadableFile(string path) returns ReadableByteChannel|ErrorRetrieves a readable byte channel from a given file path.
io:ReadableByteChannel readableFieldResult = check io:openReadableFile("./files/sample.txt");
Parameters
- path string - The relative or absolute file path
Return Type
- ReadableByteChannel|Error - The
io:ReadableByteChannelrelated to the given file or else anio:Errorif there is an error while opening
openWritableCsvFile
function openWritableCsvFile(string path, Separator fieldSeparator, string charset, int skipHeaders, FileWriteOption option) returns WritableCSVChannel|ErrorRetrieves a writable CSV channel from a given file path.
io:WritableCSVChannel wCsvChannel = check io:openWritableCsvFile(srcFileName);
Parameters
- path string - The CSV file path
- fieldSeparator Separator (default ",") - CSV record separator (i.e., comma or tab)
- charset string (default "UTF-8") - The character encoding used to read the file
- skipHeaders int (default 0) - Number of headers, which should be skipped
- option FileWriteOption (default OVERWRITE) - 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:Errorif any error occurred
openWritableFile
function openWritableFile(string path, FileWriteOption option) returns WritableByteChannel|ErrorRetrieves a writable byte channel from a given file path.
io:WritableByteChannel writableFileResult = check io:openWritableFile("./files/sampleResponse.txt");
Parameters
- path string - The relative or absolute file path
- option FileWriteOption (default OVERWRITE) - Indicate whether to overwrite or append the given content
Return Type
- WritableByteChannel|Error - The
io:WritableByteChannelrelated to the given file or else anio:Errorif any error occurred
print
function print(Printable... values)Prints any, error, or string template value(s) to the standard output stream.
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 value(s) to the standard output stream and terminates the 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 stringReads a line of input from the standard input (STDIN). If an argument is provided, it will be printed as a prompt before reading the input.
string choice = io:readln("Enter choice 1 - 5: "); string choice = io:readln();
Parameters
- a any? (default ()) - An optional value to be printed before reading the input
Return Type
- string - Input read from the STDIN
Classes
io: BlockStream
A stream of Block objects that is used to read the byte content from the streams.
Constructor
Initializes a stream of Block objects.
init (ReadableByteChannel readableByteChannel, int blockSize)- readableByteChannel ReadableByteChannel - The
io:ReadableByteChannelthat this block stream is referred to
- blockSize int - The size of a block as an integer
next
Reads the next block of the stream.
Return Type
close
function close() returns Error?Closes the stream manually. If not invoked, the stream closes automatically upon reaching end-of-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
A stream of CSV records that is used to read the CSV content from the streams.
Constructor
Initializes a stream of CSV records.
init (ReadableTextRecordChannel readableTextRecordChannel)- readableTextRecordChannel ReadableTextRecordChannel - The
io:ReadableTextRecordChannelthat this CSV stream is referred to
next
Reads the next CSV record of the stream.
Return Type
close
function close() returns Error?Closes the stream manually. If not invoked, the stream closes automatically upon reaching end-of-stream.
Return Type
- Error? -
()when the closing was successful or anio:Error
io: LineStream
A stream of strings(lines) that is used to read the character content from the streams.
Constructor
Initializes A stream of strings(lines).
init (ReadableCharacterChannel readableCharacterChannel)- readableCharacterChannel ReadableCharacterChannel - The
io:ReadableCharacterChannelthat the line stream is referred to
next
Reads the next line of the stream.
Return Type
close
function close() returns Error?Closes the stream manually. If not invoked, the stream closes automatically upon reaching end-of-stream.
Return Type
- Error? -
()when the closing was successful or anio:Error
io: ReadableByteChannel
Represents a readable byte channel that 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.
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
Reads 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 - Represents the number of bytes, which should be read. This should be a positive integer.
Return Type
- byte[]|Error - Content (the number of bytes) read, an
EofErroronce the channel reaches the end or else anio:Error
readAll
function readAll() returns readonly & byte[]|ErrorReads 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
bytearray or else anio:Error
blockStream
Returns 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 - The size of the block. This should be a positive integer.
base64Encode
function base64Encode() returns ReadableByteChannel|ErrorEncodes a given io:ReadableByteChannel using the Base64 encoding scheme.
io:ReadableByteChannel|Error encodedChannel = readableByteChannel.base64Encode();
Return Type
- ReadableByteChannel|Error - An encoded
io:ReadableByteChannelor else anio:Error
base64Decode
function base64Decode() returns ReadableByteChannel|ErrorDecodes a given Base64 encoded io:ReadableByteChannel.
io:ReadableByteChannel|Error encodedChannel = readableByteChannel.base64Decode();
Return Type
- ReadableByteChannel|Error - A decoded
io:ReadableByteChannelor else anio:Error
close
function close() returns Error?Closes the readable byte channel to release any underlying resources. After a channel is closed, any further reading operations will cause an error.
io:Error? err = readableByteChannel.close();
Return Type
- Error? -
()or else anio:Errorif any error occurred
io: ReadableCharacterChannel
Represents a channel, which could be used to read characters through a given ReadableByteChannel.
Constructor
Initializes a readable character channel.
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
Reads the entire channel content as a string.
string|io:Error content = readableCharChannel.readString();
readAllLines
Reads the entire channel content as a list of lines.
string[]|io:Error content = readableCharChannel.readAllLines();
Return Type
readJson
function readJson() returns json|ErrorReads 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 the value of a specified property key from a properties file. If the key is not found, the provided default value is returned.
string|io:Error result = readableCharChannel.readProperty(key, defaultValue);
Parameters
- key string - The property key to look up in the properties file
- defaultValue string (default "") - The default value to return if the key is not found
lineStream
Returns 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:Errorif any error occurred
io: ReadableCSVChannel
Represents a readable CSV channel which could be used to read records from CSV file.
Constructor
Initializes a readable CSV channel.
init (ReadableCharacterChannel byteChannel, Separator fs, int nHeaders)- byteChannel ReadableCharacterChannel - The
io:ReadableCharacterChannel, which will represent the content in the CSV file
- fs Separator "," - The 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 booleanChecks if there is another record available to be read from the CSV channel.
boolean hasNext = readableCSVChannel.hasNext();
Return Type
- boolean - True if there is another record available
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 readable CSV channel to release any underlying resources. After a channel is closed, any further reading operations will cause an error.
io:Error? err = readableCSVChannel.close();
Return Type
- Error? - An
io:Errorif any error occurred
getTable
function getTable(typedesc<record {}> structType, string[] fieldNames) returns table<record {}>|ErrorReturns 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 {}>|ErrorReturns 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 a readable data channel.
init (ReadableByteChannel byteChannel, ByteOrder bOrder)- byteChannel ReadableByteChannel - The
io:ReadableByteChannelchannel, which would represent the source to read/write data
- bOrder ByteOrder "BE" - The byte order used for reading data. Defaults to
"BE"(Big Endian)
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();
Return Type
readString
Reads the string value represented through the provided number of bytes.
string|io:Error string = dataChannel.readString(10, "UTF-8");
Parameters
- nBytes int - The number of bytes to read from the data channel to construct the string
- encoding string - The character encoding to use for decoding the bytes into a string (e.g., "UTF-8")
Return Type
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:Errorif any error occurred
io: ReadableTextRecordChannel
Represents a readable record channel.
Constructor
Initializes a readable text record channel.
init (ReadableCharacterChannel charChannel, string fs, string rs, string fmt)- charChannel ReadableCharacterChannel - The
io:ReadableCharacterChannelwhich will point to the input/output resource
- fs string "" - The field separator (this could be a regex)
- rs string "" - The record separator (this could be a regex)
- fmt string "default" -
hasNext
function hasNext() returns booleanChecks 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
Reads 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:Errorif any error occurred
io: StringReader
Represents a reader which will wrap string content as a channel.
readJson
function readJson() returns json|ErrorReads 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:Errorif 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:Errorif any error occurred
io: WritableByteChannel
Represents a writable byte channel that acts as an output resource (e.g., a file) for writing bytes.
A file path can be used to obtain an io:WritableByteChannel.
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:Errorif any error occurred
io: WritableCharacterChannel
Represents a writable character channel used for writing characters.
Constructor
Initializes a writable character channel.
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 sequence of characters (string) to the writable character channel.
int|io:Error result = writableCharChannel.write("Content", 0);
Parameters
- content string - The string content to be written
- startOffset int - The number of characters to skip from the beginning of the content before writing
Return Type
writeLine
Writes a string as a line followed by a newline character (\n) to the writable character channel.
io:Error? result = writableCharChannel.writeLine("Content");
Parameters
- content string - The string content to be written
Return Type
- Error? -
()if the writing was successful or anio:Error
writeJson
function writeJson(json content) returns Error?Writes the provided JSON content to the writable character channel.
io:Error? err = writableCharChannel.writeJson(inputJson, 0);
Parameters
- content json - The JSON content to be written
Return Type
- Error? -
()if the writing was successful or anio:Error
writeXml
function writeXml(xml content, XmlDoctype? xmlDoctype) returns Error?Writes the provided XML content to the writable character channel.
io:Error? err = writableCharChannel.writeXml(inputXml, 0);
Parameters
- content xml - The XML content to be written
- xmlDoctype XmlDoctype? (default ()) - An optional argument to specify the XML DOCTYPE configurations for the XML content
Return Type
- Error? -
()or else anio:Errorif any error occurred
writeProperties
Writes a key-value pair map (map<string>) to a property file.
io:Error? err = writableCharChannel.writeProperties(properties);
Parameters
- comment string - A comment describing the property list to be included
Return Type
- Error? -
()or else anio:Errorif any error occurred
close
function close() returns Error?Closes the character channel. After a channel is closed, any further writing operations will cause an error.
io:Error err = writableCharChannel.close();
Return Type
- Error? -
()or else anio:Errorif any error occurred
io: WritableCSVChannel
Represents a writable CSV channel, which could be used to write records from the CSV file.
Constructor
Initializes a writable CSV channel.
init (WritableCharacterChannel characterChannel, Separator fs)- characterChannel WritableCharacterChannel -
- fs Separator "," - The 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:Errorif the record could not be written properly
close
function close() returns Error?Closes the writable CSV channel. After a channel is closed, any further writing operations will cause an error.
io:Error? err = csvChannel.close();
Return Type
- Error? -
()or else anio:Errorif any error occurred
io: WritableDataChannel
Represents a writable data channel used for writing various types of data.
Constructor
Initializes a writable data channel.
init (WritableByteChannel byteChannel, ByteOrder bOrder)- byteChannel WritableByteChannel - The
io:WritableByteChannel, which would represent the source to read/write data
- bOrder ByteOrder "BE" - The network byte order, which specifies the order of bytes (e.g.,
io:BIG_ENDIANorio:LITTLE_ENDIAN)
writeInt16
Writes a 16 bit integer value to the writable data channel.
io:Error? err = dataChannel.writeInt16(length);
Parameters
- value int - The 16-bit integer value to be written to the data channel
Return Type
- Error? -
()if the content is written successfully or else anio:Errorif any error occurred
writeInt32
Writes a 32 bit integer value to the writable data channel.
io:Error? err = dataChannel.writeInt32(length);
Parameters
- value int - The 32-bit integer value to be written to the data channel
Return Type
- Error? -
()if the content is written successfully or else anio:Errorif any error occurred
writeInt64
Writes a 64 bit integer value to the writable data channel.
io:Error? err = dataChannel.writeInt64(length);
Parameters
- value int - The 64-bit integer value to be written to the data channel
Return Type
- Error? -
()if the content is written successfully or else anio:Errorif any error occurred
writeFloat32
Writes a 32 bit float value to the writable data channel.
io:Error? err = dataChannel.writeFloat32(3.12);
Parameters
- value float - The 32-bit float value to be written to the data channel
Return Type
- Error? -
()if the float is written successfully or else anio:Errorif any error occurred
writeFloat64
Writes a 64 bit float value to the writable data channel.
io:Error? err = dataChannel.writeFloat64(3.12);
Parameters
- value float - The 64-bit float value to be written to the data channel
Return Type
- Error? -
()if the float is written successfully or else anio:Errorif any error occurred
writeBool
Writes a boolean value to the writable data channel.
io:Error? err = dataChannel.writeInt64(length);
Parameters
- value boolean - The boolean value to be written to the data channel
Return Type
- Error? -
()if the content is written successfully or else anio:Errorif any error occurred
writeString
Writes a string value to the writable data channel.
io:Error? err = dataChannel.writeString(record);
Parameters
- value string - The string value to be written to the data channel
- encoding string - The encoding, which will represent the value string
Return Type
- Error? -
()if the content is written successfully or else anio:Errorif any error occurred
writeVarInt
Writes a variable-length integer to the writable data channel.
io:Error? err = dataChannel.writeVarInt(length);
Parameters
- value int - The variable-length integer value to be written to the data channel
Return Type
- Error? -
()if the integer is written successfully, or anio:Errorif an error occurs
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:Errorif any error occurred
io: WritableTextRecordChannel
Represents a writable text record channel that allows writing records.
Constructor
Initializes a writable text record channel.
init (WritableCharacterChannel characterChannel, string fs, string rs, string fmt)- characterChannel WritableCharacterChannel - The
io:WritableCharacterChannel, which will point to the input/output resource
- fs string "" - The field separator (this could be a regex)
- rs string "" - The 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:Errorif 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:Errorif 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
Represents 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
Specifies the format used to represent CSV data.
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: about 1 month ago
Version: 1.8.1
License: Apache-2.0
Compatibility
Platform: java21
Ballerina version: 2201.12.0
GraalVM compatible: Yes
Pull count
Total: 39239
Current verison: 0
Weekly downloads
Keywords
io
json
xml
csv
file
Contributors