How to delete file on remote server using SFTP in java?

Deleting or removing a file on remote server in java is easy using JSCH (SFTP) api. Now-a-days it is a common use case in software projects where you need to delete a file from the remote server using SFTP connection.

JSch is a pure Java implementation of SSH2 (We can use SFTP Channel). JSch allows you to connect to an sshd server and use port forwarding, X11 forwarding, file transfer, etc., and you can integrate its functionality into your own Java programs. JSch is licensed under BSD style license.

Below java code shows you how you can delete or remove a file from remote server using SFTP connection in java code.

* Created on Jan 4, 2017 Copyright(c) All Rights Reserved.
package com.kodehelp.sftp;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
 * @author
public class DeleteFileFromSFTPServer {
    static Session session = null;
    static Channel channel = null;
    static ChannelSftp channelSftp = null;
    public static void main(String[] args) {
        String SFTPHOST = ""; // SFTP Host Name or SFTP Host IP Address
        int SFTPPORT = 22; // SFTP Port Number
        String SFTPUSER = "username"; // User Name
        String SFTPPASS = "password"; // Password
        String SFTPWORKINGDIR = "/home/kodehelp/download"; // Source Directory on SFTP server in which the file is
                                                           // located on remote server
        boolean deletedflag = false;
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.connect(); // Create SFTP Session
            channel = session.openChannel("sftp"); // Open SFTP Channel
            channelSftp = (ChannelSftp) channel;
  ; // Change Directory on SFTP Server
            channelSftp.rm("latest.tar.gz"); // This method removes the file from remote server
            deletedflag = true;
            if (deletedflag) {
                System.out.println("File deleted successfully.");
        } catch (Exception ex) {
        } finally {
            if (channelSftp != null)
            if (channel != null)
            if (session != null)