从SFTP服务器下载所有文件的Java代码:

huangapple 未分类评论60阅读模式
英文:

downloading all files from sftp server in java

问题

以下是您的代码的翻译部分:

package svb.ftp.bs.load;

import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;

import java.io.FileNotFoundException;
import java.io.File;
import java.io.FileInputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;

import java.io.InputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import java.util.List;

import org.apache.commons.net.ftp.FTP;

import org.apache.commons.io.IOUtils;

import org.junit.Test;

import java.util.Vector;

public class downloadFtp {

    public static void main(String[] args) {

        String SFTPHOST = "host";
        int SFTPPORT = 22;
        String SFTPUSER = "user";
        String SFTPPASS = "Pass";
        String privateKey = "E:\\Oracle\\mywork\\DownloadFTP\\ppk.ppk";
        String SFTPWORKINGDIR = "Inbox/ARR_SI_MedicalTranscriptionBillCorp_PD_20200724_32137.TXT";

        com.jcraft.jsch.Session session = null;
        Channel channel = null;
        ChannelSftp channelSftp = null;
        JSch jsch = new JSch();
        try {
            jsch.addIdentity(privateKey);
            session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
            session.setPassword(SFTPPASS);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            channel = session.openChannel("sftp");
            channel.connect();
            System.out.println("Connected");
            channelSftp = (ChannelSftp) channel;
            channelSftp.cd(SFTPWORKINGDIR);

            
            InputStream is = channelSftp.get(SFTPWORKINGDIR);
            IOUtils.copy(is, System.out);
            is.close();


            System.out.println("File Uploaded to FTP Server Sucessfully.");
        } catch (JSchException jse) {
            // TODO: Add catch code
            jse.printStackTrace();
        } catch (SftpException se) {
            // TODO: Add catch code
            se.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

您提供的错误信息如下:

4: Can't change directory: /Inbox/ARR_SI_MedicalTranscriptionBillCorp_PD_20200724_32137.TXT
	at com.jcraft.jsch.ChannelSftp.cd(ChannelSftp.java:350)
	at svb.ftp.bs.load.downloadFtp.main(downloadFtp.java:67)
Process exited with exit code 0.

由于您的代码是从SFTP服务器下载文件,但是您尝试使用cd命令切换到文件的路径上。这是不正确的,因为您只需要提供远程文件的路径来下载它,而不是切换到该目录。如果您想要下载指定路径下的所有文件,您需要列出目录中的文件列表,然后逐个下载。

英文:

I am trying to Download All files from folder on SFTP server , Below is my Code Please suggest changes so i can download All available files from remote directory and can save to Local Directory

package svb.ftp.bs.load;

import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;

import java.io.FileNotFoundException;
import java.io.File;
import java.io.FileInputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;

import java.io.InputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import java.util.List;

import org.apache.commons.net.ftp.FTP;

import org.apache.commons.io.IOUtils;

import org.junit.Test;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

import java.io.IOException;
import java.io.InputStream;

import java.util.Vector;

public class downloadFtp {

    public static void main(String[] args) {

        String SFTPHOST = "host";
        int SFTPPORT = 22;
        String SFTPUSER = "user";
        String SFTPPASS = "Pass";
        String privateKey = "E:\\Oracle\\mywork\\DownloadFTP\\ppk.ppk";
        String SFTPWORKINGDIR = "Inbox/ARR_SI_MedicalTranscriptionBillCorp_PD_20200724_32137.TXT";

        com.jcraft.jsch.Session session = null;
        Channel channel = null;
        ChannelSftp channelSftp = null;
        JSch jsch = new JSch();
        try {
            jsch.addIdentity(privateKey);
            session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
            session.setPassword(SFTPPASS);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            channel = session.openChannel("sftp");
            channel.connect();
            System.out.println("Connected");
            channelSftp = (ChannelSftp) channel;
            channelSftp.cd(SFTPWORKINGDIR);

            
            InputStream is = channelSftp.get(SFTPWORKINGDIR);
            IOUtils.copy(is, System.out);
            is.close();


            System.out.println("File Uploaded to FTP Server Sucessfully.");
        } catch (JSchException jse) {
            // TODO: Add catch code
            jse.printStackTrace();
        } catch (SftpException se) {
            // TODO: Add catch code
            se.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
       

    }
}

Currently when i run the code it show below error

4: Can't change directory: /Inbox/ARR_SI_MedicalTranscriptionBillCorp_PD_20200724_32137.TXT
	at com.jcraft.jsch.ChannelSftp.cd(ChannelSftp.java:350)
	at svb.ftp.bs.load.downloadFtp.main(downloadFtp.java:67)
Process exited with exit code 0.

答案1

得分: 3

以下是翻译好的内容:


堆栈跟踪正在告诉您出了什么问题。

> 无法更改目录:/收件箱/ARR_SI_MedicalTranscriptionBillCorp_PD_20200724_32137.TXT

问题出在:

channelSftp.cd(SFTPWORKINGDIR);

在这里,您正在传递文件名,但它期望一个目录(cd 代表更改目录)。您不能将 CD 用于文件。

如果传递文件夹/路径,它会起作用。请尝试以下内容:

channelSftp.cd("/收件箱/一个文件夹/");

如何下载全部:
参考:https://ganeshtiwaridotcomdotnp.blogspot.com/2020/07/download-files-from-ftp-using-jsch-java.html

为了下载所有文件,首先列出根文件夹中的所有文件,遍历它...如果是文件,则下载;如果是文件夹,则列出内容,并对子文件夹进行递归操作。

以下是如何从指定文件夹下载文件的示例:

import com.jcraft.jsch.*;
import java.util.Properties;
import java.util.Vector;

public class JschDownload {

    public static void main(String[] args) {

        Session session = null;
        Channel channel = null;
        JSch jsch = new JSch();
        try {
            session = jsch.getSession("demo", "test.rebex.net", 22);
            session.setPassword("password");
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            System.out.println("会话已连接");

            channel = session.openChannel("sftp");
            channel.connect();
            System.out.println("已连接");

            ChannelSftp channelSftp = (ChannelSftp) channel;
            downloadFromFolder(channelSftp, "/");
            downloadFromFolder(channelSftp, "/pub/example/");

            System.out.println("文件已成功上传到FTP服务器。");
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (channel != null) {
                channel.disconnect();
            }
            session.disconnect();
        }

    }

    static void downloadFromFolder(ChannelSftp channelSftp, String folder) throws SftpException {
        Vector<ChannelSftp.LsEntry> entries = channelSftp.ls(folder);
        System.out.println(entries);

        // 从根文件夹下载所有文件
        for (ChannelSftp.LsEntry en : entries) {
            if (en.getFilename().equals(".") || en.getFilename().equals("..") || en.getAttrs().isDir()) {
                continue;
            }

            System.out.println(en.getFilename());
            channelSftp.get(folder + en.getFilename(), en.getFilename());
        }
    }

}

有关 jsch 库的示例和文档,请参考 http://www.jcraft.com/jsch/examples/


英文:

The stacktrace is telling you what's wrong.

> Can't change directory: /Inbox/ARR_SI_MedicalTranscriptionBillCorp_PD_20200724_32137.TXT

Problem is with:

channelSftp.cd(SFTPWORKINGDIR);

Here you are passing filename but its expecting a directory (cd stands for Change Directory). You cannot do CD to a file.

If you pass a folder/path it would work. Try the following :

channelSftp.cd(&quot;/Inbox/a_folder/&quot;);

How to Download All:
Reference: https://ganeshtiwaridotcomdotnp.blogspot.com/2020/07/download-files-from-ftp-using-jsch-java.html

In order to download all files, first list all files in root folder, iterate over it.. if its a file download, if its a folder list the content and keep doing it recursively for sub folders.

The following is an example of how to download files from a defined folder:

import com.jcraft.jsch.*;

import java.util.Properties;
import java.util.Vector;

public class JschDownload {

    public static void main(String[] args) {

        Session session = null;
        Channel channel = null;
        JSch jsch = new JSch();
        try {
            session = jsch.getSession(&quot;demo&quot;, &quot;test.rebex.net&quot;, 22);
            session.setPassword(&quot;password&quot;);
            Properties config = new Properties();
            config.put(&quot;StrictHostKeyChecking&quot;, &quot;no&quot;);
            session.setConfig(config);
            session.connect();
            System.out.println(&quot;session connect&quot;);


            channel = session.openChannel(&quot;sftp&quot;);
            channel.connect();
            System.out.println(&quot;Connected&quot;);

            ChannelSftp channelSftp = (ChannelSftp) channel;
            downloadFromFolder(channelSftp, &quot;/&quot;);
            downloadFromFolder(channelSftp, &quot;/pub/example/&quot;);

            System.out.println(&quot;File Uploaded to FTP Server Sucessfully.&quot;);
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (channel != null) {
                channel.disconnect();
            }
            session.disconnect();
        }

    }

    static void downloadFromFolder(ChannelSftp channelSftp, String folder) throws SftpException {
        Vector&lt;ChannelSftp.LsEntry&gt; entries = channelSftp.ls(folder);
        System.out.println(entries);

        //download all from root folder
        for (ChannelSftp.LsEntry en : entries) {
            if (en.getFilename().equals(&quot;.&quot;) || en.getFilename().equals(&quot;..&quot;) || en.getAttrs().isDir()) {
                continue;
            }

            System.out.println(en.getFilename());
            channelSftp.get(folder + en.getFilename(), en.getFilename());
        }
    }

}

Refer to http://www.jcraft.com/jsch/examples/ for examples and documentation of the jsch library.

答案2

得分: 0

以下是您提供的代码部分的翻译结果:

这是一个用于获取所有子文件夹中文件的递归方法。

private void downloadFromFolder(String remotePath, String localPath) throws SftpException {
    try {
        Vector<ChannelSftp.LsEntry> entries = channel.ls(remotePath);
        System.out.println(entries);

        // 从根文件夹下载所有内容
        for (ChannelSftp.LsEntry en : entries) {
            if (!en.getFilename().equals(".") && !en.getFilename().equals("..") && en.getAttrs().isDir()) {
                Path path = Paths.get(localPath + "\\" + en.getFilename());
                Files.createDirectories(path);
                downloadFromFolder(remotePath + "/" + en.getFilename(), path.toString());
                continue;
            }
            if (en.getFilename().equals(".") || en.getFilename().equals("..")) {
                continue;
            }

            System.out.println(en.getFilename());
            channel.get(remotePath + "/" + en.getFilename(), localPath + "\\" + en.getFilename());
        }
    } catch (Exception e) {

    }
}

请注意,我只翻译了您提供的代码部分,不包括问题或其他内容。如有需要,您可以将这些翻译应用到您的项目中。

英文:

here a recursive methode to get all files in sub folder also

private void downloadFromFolder( String remotePath, String localPath ) throws SftpException {
	 try
	 {
    Vector&lt;ChannelSftp.LsEntry&gt; entries = channel.ls(remotePath);
    System.out.println(entries);

    //download all from root folder
    for (ChannelSftp.LsEntry en : entries) {
    	if(!en.getFilename().equals(&quot;.&quot;) &amp;&amp; !en.getFilename().equals(&quot;..&quot;) &amp;&amp; en.getAttrs().isDir())
    	{
    	    Path path = Paths.get(localPath + &quot;\\&quot; + en.getFilename());
    	    Files.createDirectories(path);
    		downloadFromFolder(remotePath + &quot;/&quot; + en.getFilename(),path.toString());
    		continue;
    	}
        if (en.getFilename().equals(&quot;.&quot;) || en.getFilename().equals(&quot;..&quot;)) {
            continue;
        }

        System.out.println(en.getFilename());
        channel.get(remotePath + &quot;/&quot; + en.getFilename(), localPath + &quot;\\&quot; + en.getFilename());
    }
	 }catch(Exception e)
	 {
		 
	 }
}

huangapple
  • 本文由 发表于 2020年7月28日 23:16:41
  • 转载请务必保留本文链接:https://java.coder-hub.com/63137475.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定