連接獲取上傳sftp遠程目錄信息的工具類FtpsFileList

連接獲取上傳sftp遠程目錄信息的工具類

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.dc.path.PathError;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

public class FtpsFileList {
    private static final Logger LOG = LoggerFactory.getLogger(FtpsFileList.class);

    private static ChannelSftp sftp = null;
    private static Channel channel = null;
    private static Session sshSession = null;
    private static String src = "/home/ubuntu/test10257527";
    private static String localDownPath = "D:\\filepath\\download";
    private static String localUpPath = "D:\\filepath\\upfile";

    public static void main(String[] args) {

        channel = getChannel("10.62.118.102", 22, "ubuntu", "cloud");//serve Ip,port,username,pwd
        List<String> str = listFileNames(channel, src);
        System.out.println("目錄下包含的文件名稱爲:" + str);
        for (String a : str) {
            System.out.println("文件名爲:" + a);
        }

        //download file from serve
        getFileFromSftpServer(channel, src, localDownPath);

        //upload file to serve from local
        //putFileToSftpServer(channel,src,localUpPath);

        closeResource(channel, sftp, sshSession);
    }

    private static List<String> listFileNames(Channel channel, String dir) {
        List<String> list = new ArrayList<String>();
        ChannelSftp sftp = null;
        try {
            sftp = (ChannelSftp) channel;
            Vector vector = sftp.ls(dir);//獲取文件列表
            for (Object item : vector) {
                if (item instanceof com.jcraft.jsch.ChannelSftp.LsEntry) {
                    String fileName = ((com.jcraft.jsch.ChannelSftp.LsEntry) item).getFilename();
                    if (fileName.equals(".") || fileName.equals("..")) {
                        continue;
                    }
                    System.out.println(fileName);
                    list.add(fileName);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    private static void getFileFromSftpServer(Channel channel, String src, String localPath) {
        ChannelSftp sftp = null;

        try {
            sftp = (ChannelSftp) channel;
            Vector vector = sftp.ls(src);//獲取文件目錄下所有的文件
            for (Object item : vector) {
                if (item instanceof com.jcraft.jsch.ChannelSftp.LsEntry) {
                    String fileName = ((com.jcraft.jsch.ChannelSftp.LsEntry) item).getFilename();
                    if (fileName.equals(".") || fileName.equals("..")) {
                        continue;
                    }
                    System.out.println(fileName);
                    File localpath = new File(localPath);
                    File[] fileList = localpath.listFiles();
                    if (!localpath.exists()) {
                        localpath.mkdirs();
                        localPath = localpath.getPath();
                    }
                    for (File file : fileList) {
                        if (fileName.equals(file.getName())) {
                            file.delete();
                        }
                    }
                    System.out.println(localPath);
                    String localFileName = localPath + File.separator + fileName;

                    sftp.get(src + "/" + fileName, localPath);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

     static void putFileToSftpServer(Channel channel, String dst, String localPath,Session session) {
         File file = new File(localPath);
        try {
            sftp = (ChannelSftp) channel;
            if (!file.exists()) {
                throw new PathError("此文件爲空");
            }
         
            sftp.put(localPath, dst);
            Thread.sleep(1000);
            System.out.println("------"+localPath.substring(0,localPath.lastIndexOf(".")));
            sftp.put(localPath.substring(0,localPath.lastIndexOf(".")), dst);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            closeResource(channel,sftp,session);
            file.delete();
            //sftp.put(dst,localPath.substring(0,localPath.lastIndexOf(".")-1));
            new File(localPath.substring(0,localPath.lastIndexOf("."))).delete();
        }
    }

    private static Channel getChannel(String host, int port, String username, final String password) {

        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();
            LOG.debug("Session connected!");
            channel = sshSession.openChannel("sftp");
            channel.connect();
            LOG.debug("Channel connected!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return channel;
    }

    private static void closeResource(Channel channel, ChannelSftp sftp, Session session) {
        if (channel != null) {
            if (channel.isConnected()) {
                channel.disconnect();
            }
        }
        if (sftp != null) {
            if (sftp.isConnected()) {
                sftp.disconnect();
            }
        }
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();
            }
        }
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章