SFTP操作服务器的文件


package com.socket;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;

import org.apache.commons.lang.StringUtils;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SocketFactory;

/**
 * SFTP上传下载工具类
 * @author zhaohaoa
 */
public class SFTPConnection {
//    private static Logger log = LoggerFactory.getLogger(SFTPConnection.class);
    private Session session;
    private String host;
    private int port;
    private String username;
    private String password;
    private int timeout;
    private String localbind;

    /**
     * 构造器初始化
     * @param host 远程地址
     * @param port 远程端口
     * @param username 用户名
     * @param password 密码
     * @param timeout session超时时间
     */
    public SFTPConnection(String host, int port, String username, String password, int timeout) {
        this.host = host;
        this.port = port;
        this.username = username;
        this.password = password;
        this.timeout = timeout;
    }

    /**
     * 构造器
     * @param host
     * @param port
     * @param username
     * @param password
     */
    public SFTPConnection(String host, int port, String username, String password) {
        this(host, port, username, password, 60 * 1000);
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public String getLocalbind() {
        return localbind;
    }

    public void setLocalbind(String localbind) {
        this.localbind = localbind;
    }

    /**
     * 静态内部类,创建socket连接
     */
    public static class SFTPSocketFactoty implements SocketFactory {
        private String localbind;
        private int timeout;
        public SFTPSocketFactoty(String localbind, int timeout) {
            this.localbind = localbind;
            this.timeout = timeout;
        }

        @Override
        public Socket createSocket(String s, int i) throws IOException, UnknownHostException {
            Socket socket = new Socket();
            socket.bind(new InetSocketAddress(localbind, 0));
            socket.connect(new InetSocketAddress(s, i), timeout);
            return socket;
        }

        @Override
        public InputStream getInputStream(Socket socket) throws IOException {
            return socket.getInputStream();
        }

        @Override
        public OutputStream getOutputStream(Socket socket) throws IOException {
            return socket.getOutputStream();
        }
    }

    /**
     * 关闭sftp连接
     * 断开输入输出流,销毁session
     */
    public void disconnect() {
        if (isConnected()) {
            try {
                session.disconnect();
//                log.info("sftp disconnect host " + host + ".");
            } catch (Exception e) {
//                log.error("sftp disconnect host " + host + ". happen errors.", e);
            }
        }
    }

    /**
     * 是否连接
     */
    public boolean isConnected() {
        return session != null && session.isConnected();
    }

    /**
     * 连接sftp服务器
     * @throws Exception
     */
    public void connect() throws Exception {
        try {
//            log.info("sftp connect host " + host + "@" + username);
            JSch jsch = new JSch();
            session = jsch.getSession(username, host, port);
            session.setPassword(password);
            session.setTimeout(timeout);
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);

            if (StringUtils.isNotEmpty(localbind)) {
                session.setSocketFactory(new SFTPSocketFactoty(localbind, timeout));
            }

            session.connect();
//            log.info("sftp connect success!");
        } catch (Exception e) {
//            log.error("sftp connect fail!");
            throw e;
        }
    }


    /**
     * 上传文件
     * @param remoteDir 远程目录
     * @param localFile 本地文件(绝对地址)
     */
    public void upload(String remoteDir, String localFile) throws Exception {
        if (!isConnected()) {
            connect();
        }

        ChannelSftp sftp = null;
        FileInputStream fis = null;
        try {
            sftp = (ChannelSftp) session.openChannel("sftp");
            sftp.connect();
            sftp.setFilenameEncoding("GBK");	// 设置编码,防止上传文件名称乱码问题

            if (StringUtils.isNotEmpty(remoteDir)) {
                sftp.cd(remoteDir);
            }

            File file = new File(localFile);
            fis = new FileInputStream(file);

//            log.info("upload file[{}] to remote dir[{}]", localFile, remoteDir);
            sftp.put(fis, file.getName());
//            log.info("upload file successful.");
        } finally {
            if (fis != null) {
                fis.close();
            }
            if (sftp != null && sftp.isConnected()) {
                sftp.disconnect();
            }
        }
    }

    /**
     * 查询某个路径下的文件
     * @param remoteDir 远程服务器路径
     * @param keyword 什么类型的文件,例如.jpg的图片格式就填jpg
     * @return 返回一个list
     * @throws Exception
     */
    public List<Map> listFile(String remoteDir, String keyword) throws Exception {
        if (!isConnected()) {
            connect();
        }

        ChannelSftp sftp = null;
        List<Map> list = new ArrayList<Map>();
        try {
            sftp = (ChannelSftp) session.openChannel("sftp");
            sftp.connect();
            sftp.setFilenameEncoding("GBK");	// 设置编码,防止上传文件名称乱码问题
            if (StringUtils.isNotEmpty(remoteDir)) {
                sftp.cd(remoteDir);
            }
            Vector vec = sftp.ls(".");
//            log.info("ls remote dir[{}]", remoteDir);
            for (Iterator<LsEntry> iter = vec.iterator(); iter.hasNext(); ) {
                LsEntry en = iter.next();
                if (en.getAttrs().isDir()) {
                    continue;
                }
                if (StringUtils.isEmpty(keyword) || en.getFilename().indexOf(keyword) != -1) {
                    Map map = new HashMap();
                    list.add(map);
                    map.put("name", en.getFilename());
                    map.put("length", en.getAttrs().getSize());
                    map.put("size", getSizeName(en.getAttrs().getSize()));
                    map.put("date",getFormatDate(en.getAttrs().getMtimeString()));
                }
            }
        } finally {
            if (sftp != null && sftp.isConnected()) {
                sftp.disconnect();
            }
        }
        return list;
    }

    /**
     * 下载文件
     * @param remoteDir 远程目录
     * @param remoteFileName 文件名称
     * @param localSaveFile 本地保存文件(绝对地址)
     */
    public File download(String remoteDir, String remoteFileName, String localSaveFile) throws Exception {
        if (!isConnected()) {
            connect();
        }

        ChannelSftp sftp = null;
        FileOutputStream fos = null;
        try {
            sftp = (ChannelSftp) session.openChannel("sftp");
            sftp.connect();
            sftp.setFilenameEncoding("GBK");	// 设置编码,防止上传文件名称乱码问题
            if (StringUtils.isNotEmpty(remoteDir)) {
                sftp.cd(remoteDir);
            }

//            log.info("download remote file[{}] dir[{}] to [{}]", new String[] {remoteFileName, remoteDir, localSaveFile});
            File file = new File(localSaveFile);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            fos = new FileOutputStream(file);
            sftp.get(remoteFileName, fos);
            return file;
        } finally {
            if (fos != null) {
                fos.close();
            }
            if (sftp != null && sftp.isConnected()) {
                sftp.disconnect();
            }
        }
    }

    /**
     * 获取文件后缀
     * @param fileName
     * @return
     */
    public static String getFileExtension(String fileName) {
        int endDot = fileName.lastIndexOf(".");
        if (endDot == -1) {
            return "";
        }
        return fileName.substring(endDot, fileName.length());
    }

    /**
     * 获取文件大小名称
     * @param size
     * @return
     */
    public String getSizeName(long size) {
        int GB = 1024 * 1024 * 1024;// 定义GB的计算常量
        int MB = 1024 * 1024;// 定义MB的计算常量
        int KB = 1024;// 定义KB的计算常量
        DecimalFormat df = new DecimalFormat("0.00");// 格式化小数
        String resultSize = "";
        if (size / GB >= 1) {
            // 如果当前Byte的值大于等于1GB
            resultSize = df.format(size / (float) GB) + "GB";
        } else if (size / MB >= 1) {
            // 如果当前Byte的值大于等于1MB
            resultSize = df.format(size / (float) MB) + "MB";
        } else if (size / KB >= 1) {
            // 如果当前Byte的值大于等于1KB
            resultSize = df.format(size / (float) KB) + "KB";
        } else {
            resultSize = size + "B";
        }
        return resultSize;
    }
    /**
     * 国际化的时间格式日期转换为常见格式
     * 2018-6-13
     * @param StringDate
     * @return
     */
    public String getFormatDate(String StringDate){
        String sDate="";
        SimpleDateFormat sdf1 = new SimpleDateFormat ("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
        try
        {
            Date date=sdf1.parse(StringDate);
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sDate=sdf.format(date);
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }
        return sDate;
    }

    public static void main(String[] args) throws Exception {
		SFTPConnection sftp = new SFTPConnection("172.16.16.240", 22, "socket", "socket");
//        sftp.upload("/home/socket/file", "E:\\testpdf\\1.png");
        //sftp.upload("/home/socket/file", "E:\\CHM文件\\XMLDOM对象方法手册.chm");
		System.out.println(sftp.listFile("/home/socket/file", ""));
//		sftp.disconnect();
//		String a="Tue Jun 12 10:08:05 CST 2018";
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//		String dateStr = sdf.format(a);


    }
}

猜你喜欢

转载自blog.csdn.net/lingmao555/article/details/80741236