Search code examples
javapathsftprelative-pathapache-commons-vfs

Apache VFS relative path


I try to get folder's parent with Apache VFS using relative path, but I get "Invalid relative path"

public static void main(String[] args) throws Exception {
FileSystemManager fileSystemManager = VFS.getManager();
FileObject fileObject = fileSystemManager
.resolveFile("sftp://myuser:mypassword@myhost/"); // works!!
FileObject root = fileObject.resolveFile("../"); // fails!!
FileObject fileObjects[] = root.getChildren();
...

I tried "/.." , "/../" as well, all got exception. What is the right way to the parent directory?

P.S #getParent will not work, It's for files only, not directories.


Solution

  • Nailed it.

    public class Test {
    
        public static void main(String[] args) throws Exception {
            FileSystemOptions opts = new FileSystemOptions();
            SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
            SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, false);
            FileSystemManager fileSystemManager = VFS.getManager();
            FileObject fileObject = fileSystemManager
                    .resolveFile("sftp://user:password@host/",opts);
    
            FileObject temp = fileObject.resolveFile("/foo/faa/frog/");
            FileObject fileObjects[] = temp.getChildren();
    
            try {
                for (FileObject j : fileObjects) {
    
                    System.out.println(j.getName().getBaseName());
                    j.close();
                }
            } finally {
                fileObject.close();
                temp.close();
            }
        }
    }