Sample code for 30+ languages & platforms
Lua

Read Text from a Remote SFTP File (Sequential)

See more SFTP Examples

Demonstrates the Chilkat SFtp.ReadFileText method, which reads up to a number of bytes from the current position of an open handle and decodes them to text. The arguments are the handle, the maximum number of bytes, and the charset. This example reads in chunks until end-of-file.

Background: Reading a file in bounded chunks keeps memory use predictable regardless of file size, which is why the loop reads a fixed amount and repeats until Eof. A subtlety worth knowing: the byte limit is applied to the encoded bytes, so a chunk boundary could in principle fall in the middle of a multibyte character — accumulating the pieces and decoding the whole avoids any such issue in practice here since the text is reassembled in a StringBuilder.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- Demonstrates the SFtp.ReadFileText method, which reads up to a number of bytes from the current
-- position of an open handle and decodes them to text.  The 1st argument is the handle, the 2nd
-- is the maximum number of bytes, and the 3rd is the charset.

local sftp = chilkat.SFtp.new()

-- Connect, authenticate, and initialize the SFTP subsystem.
local port = 22
local success = sftp:connect("sftp.example.com", port)
if not success then
    print(sftp.last_error_text)
    return
end

-- Normally you would not hard-code the password in source.  You should instead obtain it
-- from an interactive prompt, environment variable, or a secrets vault.
local password = "mySshPassword"

success = sftp:authenticate_pw("mySshLogin", password)
if not success then
    print(sftp.last_error_text)
    return
end

success = sftp:initialize_sftp()
if not success then
    print(sftp.last_error_text)
    return
end

-- Open the remote file for reading.
local handle = sftp:open_file("subdir/notes.txt", "readOnly", "openExisting")
if not sftp.last_method_success then
    print(sftp.last_error_text)
    return
end

-- Read the file in chunks until end-of-file, accumulating the text.
local sbContent = chilkat.StringBuilder.new()
local chunkSize = 4096
local reading = true
while reading do
    local chunk = sftp:read_file_text(handle, chunkSize, "utf-8")
    if sftp:last_read_failed(handle) then
        print(sftp.last_error_text)
        return
    end

    sbContent:append(chunk)

    -- Stop once the end of the file has been reached.
    reading = not sftp:eof(handle)
end

success = sftp:close_handle(handle)
if not success then
    print(sftp.last_error_text)
    return
end

print(sbContent:get_as_string())

sftp:disconnect()