简体   繁体   English

当使用 Apache Commons VFS 进行 SFTP 上传时,必须面对 org.apache.commons.vfs2.FileSystemException:找不到带有 URI 的文件

[英]When SFTP Upload using Apache Commons VFS have to face org.apache.commons.vfs2.FileSystemException: Could not find file with URI

I try to upload a file from one remote server to another remote server.我尝试将文件从一台远程服务器上传到另一台远程服务器。 I use the following code for it but I have to face an "org.apache.commons.vfs2.FileSystemException".我使用以下代码,但我必须面对“org.apache.commons.vfs2.FileSystemException”。

**Exception: ** **例外: **

org.apache.commons.vfs2.FileSystemException: Could not find file with URI "sftp://root:***@111.222.333.444\root\home\tempfileholder\sample.txt" because it is a relative path, and no base URI was provided. org.apache.commons.vfs2.FileSystemException:找不到具有 URI "sftp://root:***@111.222.333.444\root\home\tempfileholder\sample.txt" 的文件,因为它是相对路径,并且没有提供了基本 URI。

also, I can't understand what hope them as base URL另外,我不明白希望它们作为基础 URL

solution, please.解决方案,请。

**Code: ** **代码: **

import java.io.File;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;

/**
 * The class SFTPUtil containing uploading, downloading, checking if file exists
 * and deleting functionality using Apache Commons VFS (Virtual File System)
 * Library
 * 
 * @author Kavindu
 * 
 */
public class SFTPUtility {

    public static void main(String[] args) {
        String hostName = "111.222.333.444";
        String username = "root";
        String password = "kkTTpp@JacobWPST";

        String localFilePath = ""C:"+File.separator+"Users"+File.separator+"kavindu"+File.separator+"Desktop"+File.separator+"temp"+File.separator+"tempdetails.txt";
        String remoteFilePath = "/root/home/tempfileholder/sample.txt";       
       
        upload(hostName, username, password, localFilePath, remoteFilePath);
        
    }

    /**
     * Method to upload a file in Remote server
     * 
     * @param hostName
     *            HostName of the server
     * @param username
     *            UserName to login
     * @param password
     *            Password to login
     * @param localFilePath
     *            LocalFilePath. Should contain the entire local file path -
     *            Directory and Filename with \\ as separator
     */
    public static void upload(String hostName, String username, String password, String localFilePath, String remoteFilePath) {

        File file = new File(localFilePath);
        if (!file.exists())
            throw new RuntimeException("Error. Local file not found");

        StandardFileSystemManager manager = new StandardFileSystemManager();

        try {
            manager.init();

            // Create local file object
            FileObject localFile = manager.resolveFile(file.getAbsolutePath());

            // Create remote file object
            FileObject remoteFile = manager.resolveFile(createConnectionString(hostName, username, password, remoteFilePath), createDefaultOptions());
            /*
             * use createDefaultOptions() in place of fsOptions for all default
             * options - Kavindu.
             */

            // Copy local file to sftp server
            remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);

            System.out.println("File upload success");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            manager.close();
        }
    }

    /**
     * Generates SFTP URL connection String
     * 
     * @param hostName
     *            HostName of the server
     * @param username
     *            UserName to login
     * @param password
     *            Password to login
     * @param remoteFilePath
     *            remoteFilePath. Should contain the entire remote file path -
     *            Directory and Filename with / as separator
     * @return concatenated SFTP URL string
     */
    public static String createConnectionString(String hostName, String username, String password, String remoteFilePath) {
        return "sftp://" + username + ":" + password + "@" + hostName + "/" + remoteFilePath;
    }

    /**
     * Method to setup default SFTP config
     * 
     * @return the FileSystemOptions object containing the specified
     *         configuration options
     * @throws FileSystemException
     */
    public static FileSystemOptions createDefaultOptions() throws FileSystemException {
        // Create SFTP options
        FileSystemOptions opts = new FileSystemOptions();

        // SSH Key checking
        SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");

        /*
         * Using the following line will cause VFS to choose File System's Root
         * as VFS's root. If I wanted to use User's home as VFS's root then set
         * 2nd method parameter to "true"
         */
        // Root directory set to user home
        SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, false);

        // Timeout is count by Milliseconds
        SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

        return opts;
    }
}

as the docs says正如 文档所说

By default, the path is relative to the user's home directory. This can be changed with:

FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(options, false);

so in you case, it is sftp://root:***@111.222.333.444\\home\\tempfileholder\\sample.txt which maps to /root/home/tempfileholder/sample.txt in your linux host.所以在你的情况下,它是sftp://root:***@111.222.333.444\\home\\tempfileholder\\sample.txt ,它映射到你的 linux 主机中的/root/home/tempfileholder/sample.txt

I also invested a lot of time using Apache vfs2 lib to connect to a SFTP server and download a file.我还投入了大量时间使用 Apache vfs2 lib 连接到 SFTP 服务器并下载文件。 Finally I switched to sshj which looks more easy to use for me:最后我切换到sshj ,它对我来说看起来更容易使用:

Maven Dependency: Maven 依赖:

    <dependency>
      <groupId>com.hierynomus</groupId>
      <artifactId>sshj</artifactId>
      <version>0.31.0</version>
    </dependency>

Example download a remote file:示例下载远程文件:

@Test
public void testConnection() {
    try {

        final SSHClient ssh = new SSHClient();
        ssh.addHostKeyVerifier(new PromiscuousVerifier());

        try {
            ssh.loadKnownHosts();
            ssh.connect(ftpServer, ftpPort);
            ssh.authPassword(ftpUser, ftpPassword);
            SFTPClient sftpClient = ssh.newSFTPClient();
            String localDir="/tmp/";
            sftpClient.get(ftpFullPath, localDir + "sshjFile.txt");
            sftpClient.close();
        } finally {
            ssh.disconnect();
        }
    } catch (IOException e) {
        Assert.fail(e.getMessage());
        e.printStackTrace();
    }

}

To upload a file just use the put method instead of get .要上传文件,只需使用put方法而不是get

<!--Supported protocols include: Echo, Finger, FTP, NNTP, NTP, POP3(S), SMTP(S), Telnet, Whois-->
<dependency>
  <groupId>commons-net</groupId>
  <artifactId>commons-net</artifactId>
</dependency>

add this in your pom在你的 pom 中添加这个

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 org.apache.commons.vfs2.FileSystemException:无法连接到 SFTP 服务器 - org.apache.commons.vfs2.FileSystemException: Could not connect to SFTP server Android + JCraft JSch SFTP上传-“ org.apache.commons.vfs2.FileSystemException:无法在以下位置连接到SFTP服务器” - Android + JCraft JSch SFTP upload - “org.apache.commons.vfs2.FileSystemException: Could not connect to SFTP server at…” org.apache.commons.vfs.FileSystemException:无法在端口 21 上的“sftp://username:***@114.XX.XX.XX/”连接到 SFTP 服务器 - org.apache.commons.vfs.FileSystemException: Could not connect to SFTP server at "sftp://username:***@114.XX.XX.XX/" on port 21 SFTP上传下载使用Apache Commons VFS进行存在和移动 - SFTP Upload Download Exist and Move using Apache Commons VFS java.lang.NoClassDefFoundError:org / apache / commons / vfs / FileSystemException - java.lang.NoClassDefFoundError: org/apache/commons/vfs/FileSystemException 使用Apache Commons Vfs2的SFTP文件传输 - SFTP file transfer using Apache Commons Vfs2 Apache Commons VFS 与 Quercus - Apache Commons VFS with Quercus 使用 Apache Commons VFS-SFTP,上传到服务器 - Using Apache Commons VFS- SFTP, uploading to a server 使用Apache Commons VFS中断从SFTP中复制 - Copy from SFTP interrupted using Apache Commons VFS 使用 Apache Commons vfs2(spring boot) 的 SFTP 文件传输失败并出现 IOException:错误 - SFTP file transfer using Apache Commons vfs2(spring boot) fails with IOException: error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM