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

DeeKay January 5, 2017 at 2:41 am · How To, SFTP

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) https://kodehelp.com 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 https://kodehelp.com
 *
 */
public class DeleteFileFromSFTPServer {
	
	static Session session = null;
	static Channel channel = null;
	static ChannelSftp channelSftp = null;
	
	public static void main(String[] args) {
		
		String SFTPHOST = "10.20.30.40"; // 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);
			session.setPassword(SFTPPASS);
			java.util.Properties config = new java.util.Properties();
			config.put("StrictHostKeyChecking", "no");
			session.setConfig(config);
			session.connect(); // Create SFTP Session
			channel = session.openChannel("sftp"); // Open SFTP Channel
			channel.connect();
			channelSftp = (ChannelSftp) channel;
			channelSftp.cd(SFTPWORKINGDIR); // 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){
			ex.printStackTrace();
		}finally {
			if (channelSftp != null)
				channelSftp.disconnect();
			if (channel != null)
				channel.disconnect();
			if (session != null)
				session.disconnect();

		}

	}

}