SFTP 작업 서버 파일

11168 단어 자바
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 listFile(String remoteDir, String keyword) throws Exception {
        if (!isConnected()) {
            connect();
        }

        ChannelSftp sftp = null;
        List list = new ArrayList();
        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 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);


    }
}

좋은 웹페이지 즐겨찾기