Writing code in java: How to delete files from the server in the form of sftp?

In Java, you can use the JSch library to delete files on the server through the SFTP protocol. Here is a simple sample code:

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class SFTPFileDeleter {     public static void main(String[] args) {         String host = "server hostname or IP address";         int port = 22;         String username = "username";         String password = "password";




        String filePath = "/path of the file to be deleted/name of the file";

        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(username, host, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();

            ChannelSftp sftpChannel = (ChannelSftp) channel;
            sftpChannel.rm(filePath);

            sftpChannel.disconnect();
            session.disconnect();

            System.out.println("File deleted successfully!");
        } catch (Exception e) {             e.printStackTrace();         }     } }



jsch.jarPlease make sure you have added the library to your project before running the code . You also need to replace the server hostname, port, username, password, and path to the file to delete in the code. Running this code will delete the specified file on the server.

Note: In order for this code to execute smoothly, make sure that the SSH service has been installed and running on the server, and the SFTP protocol is allowed for file transfer and deletion operations.

Guess you like

Origin blog.csdn.net/gb4215287/article/details/132265967