user2852305
user2852305

Reputation: 173

How to append data in a SFTP server file using Java

I have tried all possible ways to append some content to a file present in SFTP file path. I have got success message but not able to find that file updated. Not sure what is the reason.

Please find my code below:

jsch = new JSch();
jsch.addIdentity(privateKey); 
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
ProxyHTTP  proxy = new ProxyHTTP(PROXY, 8080);
session.setProxy(proxy);

session.setConfig("StrictHostKeyChecking", "no");
session.setConfig("cipher.s2c", "aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc,aes192-cbc,aes256-cbc,aes256-ctr");
session.setConfig("cipher.c2s", "aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc,aes192-cbc,aes256-cbc,aes256-ctr");
session.connect();

sftpChannel = (ChannelSftp)session.openChannel("sftp");
sftpChannel.connect();
if(sftpChannel.getSession().isConnected())
    logger.debug("Remote session established through the channel");

sftpChannel.cd(remoteDirectory);

List<String> list = new ArrayList<>();

ChannelSftp sftp = (ChannelSftp) sftpChannel;
Vector<LsEntry> files = sftp.ls(remoteDirectory);

for (LsEntry entry : files)
{
    if (!entry.getFilename().equals(".") && !entry.getFilename().equals(".."))
    {
        list.add(entry.getFilename());
    }
}

System.out.println(list);

InputStream stream = sftp.get(remoteDirectory + remoteFile);
try {
    BufferedReader br = new BufferedReader(new InputStreamReader(stream));
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
    // read from br
} finally {
    stream.close();
}
Files.write(Paths.get(remoteFile), "CH|OK|en,ch,de,it|CH ".getBytes(), StandardOpenOption.APPEND);
System.out.println("added country to remote path");
sftpChannel.exit();
session.disconnect();

Upvotes: 1

Views: 3227

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202292

Use one of the ChannelSftp.put method overloads with mode parameter set to ChannelSftp.APPEND.

For example:

String s = "CH|OK|en,ch,de,it|CH ";

sftp.put(new ByteArrayInputStream(s.getBytes()), remoteFile, ChannelSftp.APPEND);

Note that your code not even remotely does what you want. Files.write writes a local file, not a remote one.


Obligatory warning: Do not use StrictHostKeyChecking=no to blindly accept all host keys. That is a security flaw. You lose a protection against MITM attacks.

For a correct (and secure) approach, see:
How to resolve Java UnknownHostKey, while using JSch SFTP library?

Upvotes: 3

Related Questions