java实现ftp下文件的上传、下载和删除

有时候项目需要对服务器的文件进行操作,如下是我在项目中的应用:
需要的包为:

<dependency>
      <groupId>com.jcraft</groupId>
       <artifactId>jsch</artifactId>
       <version>0.1.49</version>
 </dependency>
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import java.io.*;
import java.util.Properties;
import java.util.Vector;

public class FileTool {

    /**
     * 上传文件到ftp服务器
     * @param host ftp服务器地址
     * @param port ftp服务器端口号
     * @param username ftp登录账号
     * @param password ftp登录密码
     * @param dir 保存文件的ftp目录
     * @param filename 保存在ftp里的文件名
     * @param originfilename 上传文件的名称(绝对地址)
     * @return
     */
    public static boolean uploadFile(String host, int port, String username, final String password, String dir,
                                             String filename,
                                             String originfilename ) {
        boolean flag = false;
        ChannelSftp sftp = null;
        Channel channel = null;
        Session sshSession = null;
        try {
            JSch jsch = new JSch();
            jsch.getSession(username, host, port);
            sshSession = jsch.getSession(username, host, port);
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
            if(sftp.ls(dir).size()==0){
                sftp.mkdir(dir);
            }
            sftp.cd(dir);
            InputStream inputStream = new FileInputStream(new File(originfilename));
            sftp.put(inputStream,filename);
            inputStream.close();
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeChannel(sftp);
            closeChannel(channel);
            closeSession(sshSession);
        }
        return flag;
    }

    /**
     * 从服务器下载文件
     * @param host ftp服务器地址
     * @param port ftp服务器端口号
     * @param username ftp登录账号
     * @param password ftp登录密码
     * @param dir 保存文件的ftp目录
     * @param filename 保存在ftp里的文件名
     * @param localPath 保存文件到本地的目录
     * @return
     */
    public static boolean downloadFile(String host, int port, String username, final String password, String dir,
                                     String filename,
                                     String localPath) {
        boolean flag = false;
        ChannelSftp sftp = null;
        Channel channel = null;
        Session sshSession = null;
        try {
            JSch jsch = new JSch();
            jsch.getSession(username, host, port);
            sshSession = jsch.getSession(username, host, port);
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
            sftp.setFilenameEncoding("UTF-8");
            sftp.cd(dir);
            Vector<?> vector = sftp.ls(dir);
            for (Object item:vector) {
                LsEntry entry = (LsEntry) item;
                if(filename.equals(entry.getFilename())){
                    File localFile = new File(localPath + File.separatorChar+ entry.getFilename());
                    OutputStream os = new FileOutputStream(localFile);
                    System.out.println(os);
                    sftp.get(filename,os);
                    os.close();
                }
                System.out.println(entry.getFilename());
            }
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeChannel(sftp);
            closeChannel(channel);
            closeSession(sshSession);
        }
        return flag;
    }

    /**
     * 删除服务器上的文件
     * @param host
     * @param port
     * @param username
     * @param password
     * @param dir 删除文件的ftp路径
     * @param filename 文件名
     * @return
     */
    public static boolean deleteFile(String host, int port, String username, final String password, String dir,
                                     String filename){
        boolean flag=false;
        ChannelSftp sftp = null;
        Channel channel = null;
        Session sshSession = null;
        try {
            JSch jsch = new JSch();
            jsch.getSession(username, host, port);
            sshSession = jsch.getSession(username, host, port);
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
            if(sftp.ls(dir).size()==0){
                sftp.mkdir(dir);
            }
            sftp.cd(dir);
            sftp.rm(dir+"/"+filename+".jpg");
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeChannel(sftp);
            closeChannel(channel);
            closeSession(sshSession);
        }
        return flag;
    }

    public static void closeChannel(Channel channel) {
        if (channel != null) {
            if (channel.isConnected()) {
                channel.disconnect();
            }
        }
    }

    public static void closeSession(Session session) {
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();
            }
        }
    }

}

在用的时候直接调用即可:

FileTool.downloadFile("127.0.0.0",22,"root","root","/usr/tomcat/webapps/99jiaeduLogo","1231243.jpg","d:\99jiaeduLogo");
FileTool.uploadFile("127.0.0.0",22,"root","root","/usr/tomcat/webapps/99jiaeduLogo","1231243.jpg","d:\99jiaeduLogo");
FileTool.deleteFile("127.0.0.0",22,"root","root","/usr/tomcat/webapps/99jiaeduLogo","12314134134");
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值