当前位置: 首页 > 面试题库 >

SFTP上传下载使用Apache Commons VFS存在并移动

梅欣然
2023-03-14
问题内容

我需要一个纯Apache Commons VFS解决方案/代码/示例

  1. 将本地文件上传到远程主机位置
  2. 检查远程主机位置中是否存在文件
  3. 将远程主机文件下载到本地文件位置
  4. 将文件从一个远程位置移动到同一主机中的另一个位置
  5. 从远程主机位置删除文件

通过SFTP调用。

该解决方案应仅使用Apache Commons VFS api,并且不应引用基础JSCH库。


问题答案:

下面的SFTP实用工具提供了上载,存在,下载,移动和删除操作的示例。我已经在几个项目中使用了它。以下代码仅使用来自Apache Commons
VFS库的api调用。

请确保将以下JAR放入项目的构建路径中:

  • commons-logging-1.1.3.jar
  • commons-vfs2-2.0.jar
  • hamcrest-core-1.3.jar
  • jsch-0.1.50.jar

任何其他兼容版本也可以。

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 Ashok
 * 
 */
public class SFTPUtility {

    public static void main(String[] args) {
        String hostName = "PutYourHostNameHere";
        String username = "PutYourUserNameForHostHere";
        String password = "PutYourPasswordForHostHere";

        String localFilePath = "C:\\FakePath\\FakeFile.txt";
        String remoteFilePath = "/FakeRemotePath/FakeRemoteFile.txt";       
        String remoteTempFilePath = "/FakeRemoteTempPath/FakeRemoteTempFile.txt";

        upload(hostName, username, password, localFilePath, remoteFilePath);
        exist(hostName, username, password, remoteFilePath);
        download(hostName, username, password, localFilePath,remoteFilePath);
        move(hostName, username, password, remoteFilePath, remoteTempFilePath);
        delete(hostName, username, password, 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
     * @param remoteFilePath
     *            remoteFilePath. Should contain the entire remote 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 - Ashok.
             */

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

    public static boolean move(String hostName, String username, String password, String remoteSrcFilePath, String remoteDestFilePath){
        StandardFileSystemManager manager = new StandardFileSystemManager();

        try {
            manager.init();

            // Create remote object
            FileObject remoteFile = manager.resolveFile(createConnectionString(hostName, username, password, remoteSrcFilePath), createDefaultOptions());
            FileObject remoteDestFile = manager.resolveFile(createConnectionString(hostName, username, password, remoteDestFilePath), createDefaultOptions());

            if (remoteFile.exists()) {
                remoteFile.moveTo(remoteDestFile);;
                System.out.println("Move remote file success");
                return true;
            }
            else{
                System.out.println("Source file doesn't exist");
                return false;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            manager.close();
        }
    }

    /**
     * Method to download the file from remote server location
     * 
     * @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
     * @param remoteFilePath
     *            remoteFilePath. Should contain the entire remote file path -
     *            Directory and Filename with / as separator
     */
    public static void download(String hostName, String username, String password, String localFilePath, String remoteFilePath) {

        StandardFileSystemManager manager = new StandardFileSystemManager();

        try {
            manager.init();

            // Append _downlaod_from_sftp to the given file name.
            //String downloadFilePath = localFilePath.substring(0, localFilePath.lastIndexOf(".")) + "_downlaod_from_sftp" + localFilePath.substring(localFilePath.lastIndexOf("."), localFilePath.length());

            // Create local file object. Change location if necessary for new downloadFilePath
            FileObject localFile = manager.resolveFile(localFilePath);

            // Create remote file object
            FileObject remoteFile = manager.resolveFile(createConnectionString(hostName, username, password, remoteFilePath), createDefaultOptions());

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

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

    /**
     * Method to delete the specified file from the remote system
     * 
     * @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
     * @param remoteFilePath
     *            remoteFilePath. Should contain the entire remote file path -
     *            Directory and Filename with / as separator
     */
    public static void delete(String hostName, String username, String password, String remoteFilePath) {
        StandardFileSystemManager manager = new StandardFileSystemManager();

        try {
            manager.init();

            // Create remote object
            FileObject remoteFile = manager.resolveFile(createConnectionString(hostName, username, password, remoteFilePath), createDefaultOptions());

            if (remoteFile.exists()) {
                remoteFile.delete();
                System.out.println("Delete remote file success");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            manager.close();
        }
    }

    // Check remote file is exist function:
    /**
     * Method to check if the remote file exists in the specified remote
     * location
     * 
     * @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 Returns if the file exists in the specified remote location
     */
    public static boolean exist(String hostName, String username, String password, String remoteFilePath) {
        StandardFileSystemManager manager = new StandardFileSystemManager();

        try {
            manager.init();

            // Create remote object
            FileObject remoteFile = manager.resolveFile(createConnectionString(hostName, username, password, remoteFilePath), createDefaultOptions());

            System.out.println("File exist: " + remoteFile.exists());

            return remoteFile.exists();
        } 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;
    }
}


 类似资料:
  • 问题内容: 我已经通过ftp成功上传了文件,但是现在我需要通过SFTP进行上传。我可以成功连接到远程服务器,创建文件并写入文件,但是无法将现有文件从本地服务器上载到远程服务器。ftp_put是否不通过sftp连接触发? 我的代码用来写文件: 有没有人成功抓取本地文件并通过上述方法使用sftp上传?一个例子将不胜感激。 谢谢 问题答案: 通过上述方法(涉及sftp),您可以使用stream_copy

  • 我的本地计算机上有一个文件。我有一个Perl脚本可以通过SFTP连接将此文件复制到远程位置()。

  • 我正在使用JSCH从SFTP服务器下载文件。我使用单会话,多通道下载文件从不同文件夹位于SFTP。对于这个下载过程,我有一组排定的作业。每项工作将: 每次打开一个新通道()。通道名称:SFTP 使用方法获取要下载的文件总数的大小 如果size(Vector)大于零,则使用下载所有文件 最后关闭打开的通道。 在上面的过程中,大多数时候我得到的文件,找不到或没有这样的文件异常,并没有下载一些文件。 谁

  • 我让activestorage在LocalHost上使用我的Rails5.2应用程序。 null 服务器设置如下: Nginx在计算机调用上反转代理 运行的另一台计算机上的Apache 乘客 我可以在rails编写的日志文件中看到,第二个请求的响应实际上相当快:

  • 问题内容: 设置INTERNET_ACCESS等后,出现此错误。 这是我测试过的代码的另一部分,仍然收到该异常 } 问题答案: “ftp.194.90.81.149”: No address associated with hostname 您收到UnknownHostException的事实意味着ftp.194.90.81.149在DNS中不是真实的主机名。我怀疑其中的数字部分是您真正想要的。即

  • 本文向大家介绍Silverlight文件上传下载实现方法(下载保存),包括了Silverlight文件上传下载实现方法(下载保存)的使用技巧和注意事项,需要的朋友参考一下 search了非常多的文章,总算勉强实现了。有许多不完善的地方。 在HCLoad.Web项目下新建目录Pics复制一张图片到根目录下。 图片名:Bubble.jpg 右击->属性->生成操作:Resource UC_UpDown