Dart
Dart
SFTP Read Text File
See more SFTP Examples
Demonstrates how to open a text file on the SSH server and read text.Chilkat Dart Downloads
import 'package:chilkat/chilkat.dart';
void main() {
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
final sftp = CkSFtp();
// Set some timeouts, in milliseconds:
sftp.connectTimeoutMs = 5000;
sftp.idleTimeoutMs = 15000;
// Connect to the SSH server.
// The standard SSH port = 22
// The hostname may be a hostname or IP address.
final hostname = 'sftp.example.com';
final port = 22;
try {
sftp.connect(hostname, port);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
// Authenticate with the SSH server. Chilkat SFTP supports
// both password-based authenication as well as public-key
// authentication. This example uses password authenication.
try {
sftp.authenticatePw('myLogin', 'myPassword');
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
// After authenticating, the SFTP subsystem must be initialized:
try {
sftp.initializeSftp();
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
// Open a file for reading.
var handle = '';
try {
handle = sftp.openFile('myTest.txt', 'readOnly', 'openExisting');
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
// Assume the file we are reading contains the following text:
// abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ
// (in ANSI format -- i.e. one byte per char).
// Read 26 bytes:
var sText = '';
try {
sText = sftp.readFileText(handle, 26, 'ansi');
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
// Should print "abcdefghijklmnopqrstuvwxyz";
print(sText);
// Read the next 10 bytes.
try {
sText = sftp.readFileText(handle, 10, 'ansi');
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
// Should print "1234567890";
print(sText);
// Read the next 26 bytes.
try {
sText = sftp.readFileText(handle, 26, 'ansi');
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
// Should print "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
print(sText);
// Close the file.
try {
sftp.closeHandle(handle);
} on ChilkatException catch (e) {
print(e.lastErrorText);
return;
}
print('Success.');
}