【问题标题】:how to transfer a file through SFTP in java? [duplicate]如何在java中通过SFTP传输文件? [复制]
【发布时间】:2013-01-27 14:49:12
【问题描述】:

如何在java中通过SFTP传输文件?我想要 SFTP 客户端的示例代码。 我想在我的应用程序中嵌入 SFTP 服务器,并且客户端应该能够向我的应用程序发送文件。

PS:这是要求 SFTP 客户端。而且这个问题不是其他两个问题的重复。

找到以下链接以实施 SFTP。

https://codetransient.wordpress.com/2019/06/22/sftp-secured-file-transfer-protocol/

【问题讨论】:

    标签: java file sftp edi b2b


    【解决方案1】:

    试试这个代码。

    public void send (String fileName) {
        String SFTPHOST = "host:IP";
        int SFTPPORT = 22;
        String SFTPUSER = "username";
        String SFTPPASS = "password";
        String SFTPWORKINGDIR = "file/to/transfer";
    
        Session session = null;
        Channel channel = null;
        ChannelSftp channelSftp = null;
        System.out.println("preparing the host information for sftp.");
    
        try {
            JSch jsch = new JSch();
            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();
            System.out.println("Host connected.");
            channel = session.openChannel("sftp");
            channel.connect();
            System.out.println("sftp channel opened and connected.");
            channelSftp = (ChannelSftp) channel;
            channelSftp.cd(SFTPWORKINGDIR);
            File f = new File(fileName);
            channelSftp.put(new FileInputStream(f), f.getName());
            log.info("File transfered successfully to host.");
        } catch (Exception ex) {
            System.out.println("Exception found while tranfer the response.");
        } finally {
            channelSftp.exit();
            System.out.println("sftp Channel exited.");
            channel.disconnect();
            System.out.println("Channel disconnected.");
            session.disconnect();
            System.out.println("Host Session disconnected.");
        }
    }   
    

    【讨论】:

    • 我的目标目录需要 sudo 权限知道我该怎么做吗? @Dhinakar
    • 如果我不知道工作目录怎么办。我只知道文件路径?那么如何处理 cd 命令呢?
    • @DishiJain 我将目标更改为 tmp 文件夹,然后使用 jcsh 使用 sudo 执行“mv”命令到最终目标。这对我有用。
    • 这里用的是什么库?
    • JSCH 库jcraft.com/jsch
    猜你喜欢
    • 2015-08-04
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多