简体   繁体   中英

Apache Commons VFS: working with FTP

I'm trying to use Apache Commons VFS with FTP. On my FTP a have the next structure of files and folders:

/
/test
/test/in
/test/in/file1.txt
/test/in/file2.txt

I need to connect and read all files from folder /test/in (it changes all the time). Code:

        FileSystemManager fsManager = null;
        FileSystem fs = null;
        FileSystemOptions opts = new FileSystemOptions();
        fsManager = VFS.getManager();

        FileObject path = fsManager.resolveFile("ftp://user:password@my.ftp.host/test/in/", opts);

        fs = path.getFileSystem();

        //prints Connection successfully established to /test/in
        System.out.println("Connection successfully established to " + path.getName().getPath());

But I couldn't got file list, because it says that /test/in does not exist. A made some tests to check file types: System.out.println(path.getType()); with different paths. Results:

ftp://user:password@my.ftp.host/test - file

ftp://user:password@my.ftp.host/test/in - imaginary

ftp://user:password@my.ftp.host/test/in/file1.txt - file

FileType.IMAGINARY means that file does not exist. Any ideas how to work with ftp folders?

只需为ftp设置'被动'模式:

FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, true);

I had a similar kind of an issue and setting the passive mode alone did not solve it.

The folder which needed to be resolved was /FTP_HOME/data/xxxx

I was monitoring the folder using the vfs2 DefaultFileMonitor and was listening in on FileChangeEvent for no avail.

FileObject listendir =  fsManager.resolveFile("ftp://"+username+":"+password+"@"+server+"/data/" + "xxxx/",opts);

Digging a little deeper showed that FileObject 's isReadable() and exists() returned false meaning that the FileObject is not accessible. Looking at the source of AbstractFileObject , it was depending on these checks to determine the directory (Check AbstractFileObject getParent() ).

Issue was that AbstractFileObject look at the file relative to the file systems root unless it is explicitly set to use the User directory as the root, hence missing out on the file path which was passed . So the solution was to set the FtpFileSystemConfigBuilder indicating to consider user directory as the root.

FtpFileSystemConfigBuilder.getInstance( ).setUserDirIsRoot(opts,true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM