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.

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