Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list files directory/files using Apache Common vfs

i am new using Apache Common vfs, I success connect to the server I already read docs but i'm stuck in this code. How i can list directory/files?

....
Session session = null;
        FileSystemManager fsManager = null;
        FileSystem fs = null;
        try {
            String host = "host_here";
            int port = 22;

            String userStr = "user_here";
            char [] username = userStr.toCharArray();

            String passStr = "password_here";
            char [] password = passStr.toCharArray();

            session = SftpClientFactory.createConnection(host, port, username, password, null);
            //session.connect();

            System.out.println("Connected to the server");

            FileSystemOptions opts = new FileSystemOptions();
            fsManager = VFS.getManager();
            FileObject file = fsManager.resolveFile("ftp://"+userStr+":"+passStr+"@"+host+"/home/", opts);    

            // .... whats next i do here? .....

        } catch (Exception e) {
            session.disconnect();
            e.printStackTrace();
        }
...

Please help me, Thank you before :)

like image 313
fanjavaid Avatar asked Feb 18 '13 08:02

fanjavaid


1 Answers

List of files can be displayed by using FileObject#getChildren() method.

FileSystemOptions opts = new FileSystemOptions();
fsManager = VFS.getManager();

// List all the files in that directory.Try to give the directory path  
FileObject localFileObject=fsManager.resolveFile("ftp://"+userStr+":"+passStr+"@"+host+"/home");
FileObject[] children = localFileObject.getChildren();
for ( int i = 0; i < children.length; i++ ){
    System.out.println( children[ i ].getName().getBaseName() );
}
// End of List Files.

FileObject file = fsManager.resolveFile("ftp://"+userStr+":"+passStr+"@"+host+"/home/", opts);

My suggestion would be to Use JSCH framework which is best for SFTP operations. As this Apache Common VFS inherently used this framework.The complexcity will be greatly reduced by JSCH.

like image 163
SRy Avatar answered Nov 04 '22 15:11

SRy