Lianja
Lianja
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 Lianja Downloads
llSuccess = .F.
// 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.
loSftp = createobject("CkSFtp")
// Connect, authenticate, and initialize the SFTP subsystem.
lnPort = 22
llSuccess = loSftp.Connect("sftp.example.com",lnPort)
if (llSuccess = .F.) then
? loSftp.LastErrorText
release loSftp
return
endif
// 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.
lcPassword = "mySshPassword"
llSuccess = loSftp.AuthenticatePw("mySshLogin",lcPassword)
if (llSuccess = .F.) then
? loSftp.LastErrorText
release loSftp
return
endif
llSuccess = loSftp.InitializeSftp()
if (llSuccess = .F.) then
? loSftp.LastErrorText
release loSftp
return
endif
// Open the remote file for reading.
lcHandle = loSftp.OpenFile("subdir/notes.txt","readOnly","openExisting")
if (loSftp.LastMethodSuccess = .F.) then
? loSftp.LastErrorText
release loSftp
return
endif
// Read the file in chunks until end-of-file, accumulating the text.
loSbContent = createobject("CkStringBuilder")
lnChunkSize = 4096
llReading = .T.
do while llReading
lcChunk = loSftp.ReadFileText(lcHandle,lnChunkSize,"utf-8")
if (loSftp.LastReadFailed(lcHandle)) then
? loSftp.LastErrorText
release loSftp
release loSbContent
return
endif
loSbContent.Append(lcChunk)
// Stop once the end of the file has been reached.
llReading = not loSftp.Eof(lcHandle)
enddo
llSuccess = loSftp.CloseHandle(lcHandle)
if (llSuccess = .F.) then
? loSftp.LastErrorText
release loSftp
release loSbContent
return
endif
? loSbContent.GetAsString()
loSftp.Disconnect()
release loSftp
release loSbContent