Показать удаленный каталог/все файлы в Jtree

у меня возникли проблемы с использованием JSCH для извлечения файлов/папок и их заполнения в JTree. В JCH для отображения файлов используйте:

Список векторов = каналSftp.ls(путь);

Но мне нужны эти списки как тип java.io.File. Итак, я могу получить absolutePath и fileName, и я не знаю, как получить тип java.io.File.

Вот мой код, и я пытаюсь работать с локальным каталогом.

public void renderTreeData(String directory, DefaultMutableTreeNode parent, Boolean recursive) {
        File [] children = new File(directory).listFiles(); // list all the files in the directory
        for (int i = 0; i < children.length; i++) { // loop through each
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(children[i].getName());
            // only display the node if it isn't a folder, and if this is a recursive call
            if (children[i].isDirectory() && recursive) {
                parent.add(node); // add as a child node
                renderTreeData(children[i].getPath(), node, recursive); // call again for the subdirectory
            } else if (!children[i].isDirectory()){ // otherwise, if it isn't a directory
                parent.add(node); // add it as a node and do nothing else
            }
        }
    }

Пожалуйста, помогите мне, заранее спасибо :)


person fanjavaid    schedule 25.02.2013    source источник


Ответы (2)


вы можете определить некоторую переменную в своем java-бине, например

 Vector<String> listfiles=new Vector<String>(); // getters and setters

   Vector list = channelSftp.ls(path);
   setListFiles(list);  // This will list the files same as new File(dir).listFiles

в JSH вы можете указать абсолютный путь, используя ChannelSftp#realpath, но, к сожалению, нет способа получить точный файл с расширением . Но вы можете использовать что-то подобное, чтобы проверить, существовало ли это имя файла в целевом каталоге или нет.

 SftpATTRS sftpATTRS = null;
  Boolean fileExists = true;
    try {
    sftpATTRS = channelSftp.lstat(path+"/"+"filename.*");
        } catch (Exception ex) {
        fileExists = false;
    }
person SRy    schedule 25.02.2013

Попробуйте это (linux на удаленном сервере):

public static void cargarRTree(String remotePath, DefaultMutableTreeNode parent) throws SftpException { 
    //todo: change "/" por remote file.separator
    Vector<ChannelSftp.LsEntry> list = sftpChannel.ls(remotePath); // List source directory structure.
    for (ChannelSftp.LsEntry oListItem : list) { // Iterate objects in the list to get file/folder names.       
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(oListItem.getFilename());
        if (!oListItem.getAttrs().isDir()) { // If it is a file (not a directory).
            parent.add(node); // add as a child node
        } else{
            if (!".".equals(oListItem.getFilename()) && !"..".equals(oListItem.getFilename())) {
                parent.add(node); // add as a child node
                cargarRTree(remotePath + "/" + oListItem.getFilename(), node); // call again for the subdirectory
            }
        }
    }
}

После того, как вы можете вызвать этот метод как:

DefaultMutableTreeNode nroot = new DefaultMutableTreeNode(sshremotedir);                
try {
    cargarRTree(sshremotedir, nroot);
} catch (SftpException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
} 
yourJTree = new JTree(nroot);
person gopeca    schedule 03.07.2014