【问题标题】:When SFTP Upload using Apache Commons VFS have to face org.apache.commons.vfs2.FileSystemException: Could not find file with URI当使用 Apache Commons VFS 进行 SFTP 上传时,必须面对 org.apache.commons.vfs2.FileSystemException:找不到带有 URI 的文件
【发布时间】:2020-06-30 13:07:26
【问题描述】:

我尝试将文件从一台远程服务器上传到另一台远程服务器。我使用以下代码,但我必须面对“org.apache.commons.vfs2.FileSystemException”。

**例外:**

org.apache.commons.vfs2.FileSystemException:找不到具有 URI“sftp://root:***@111.222.333.444\root\home\tempfileholder\sample.txt”的文件,因为它是相对路径,并且没有提供基本 URI。

另外,我无法理解希望它们作为基本 URL 的意义

请解决。

**代码:**

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;
    }
}

【问题讨论】:

    标签: java upload sftp


    【解决方案1】:

    正如docs 所说

    By default, the path is relative to the user's home directory. This can be changed with:
    
    FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(options, false);
    

    所以在你的情况下,sftp://root:***@111.222.333.444\home\tempfileholder\sample.txt 映射到你的 linux 主机中的 /root/home/tempfileholder/sample.txt

    【讨论】:

    • 我在下载时遇到了同样的错误,然后我在下面解决了它。 SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true); 当我创建 true 它识别我的根路径然后我可以移动到 /tempFileHolder
    【解决方案2】:

    我还花费了大量时间使用 Apache vfs2 lib 连接到 SFTP 服务器并下载文件。最后我切换到sshj,这对我来说看起来更容易使用:

    Maven 依赖:

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

    下载远程文件示例:

    @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();
        }
    
    }
    

    要上传文件,只需使用put 方法而不是get

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-03
      • 2013-11-17
      • 1970-01-01
      • 1970-01-01
      • 2014-02-19
      • 1970-01-01
      • 2020-09-16
      • 2020-02-20
      相关资源
      最近更新 更多