ChannelSftp下載目錄下所有或指定文件、ChannelSftp獲取某目錄下所有文件名稱、InputStream轉File

ChannelSftp下載目錄下所有或指定文件、ChannelSftp獲取某目錄下所有文件名稱、InputStream轉File


    /**
     * ChannelSftp下載目錄下所有或指定文件
     * ChannelSftp獲取某目錄下所有文件名稱
     * InputStream轉File
     */
    public Map<String, File> downFile(String remoteDir) {
        Map<String, File> fileMap = new HashMap<>(20);
        if (StringUtil.isEmpty(remoteDir)) {
            return fileMap;
        }
        ChannelSftp channelSftp = null;
        try {
            JSch jsch = new JSch();
            Session sshSession = jsch.getSession("name", "host", 22);
            sshSession.setPassword("password");
            Properties sshConfig = new Properties();
            //當第一次連接服務器時,自動接受新的公鑰
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            channelSftp = (ChannelSftp) channel;

            //ls命令獲取文件名列表
            Vector vector = channelSftp.ls(remoteDir);
            Iterator iterator = vector.iterator();
            while (iterator.hasNext()) {
                ChannelSftp.LsEntry file = (ChannelSftp.LsEntry) iterator.next();
                //文件名稱
                String fileName = file.getFilename();
                //todo 這裏可使用if或正則不下載一些文件
                InputStream inputStream = channelSftp.get(remoteDir + fileName);
                if (inputStream != null) {
                    File newFile = new File(fileName);
                    //將InputStream轉File
                    FileUtils.copyToFile(inputStream, newFile);
                    fileMap.put(fileName, newFile);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (channelSftp != null) {
                channelSftp.exit();
            }
        }
        return fileMap;
    }
    


    pom.xml


        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.51</version>
        </dependency>

 

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