问题
i have some problem using JSCH to retrieve files/folders and populate them in JTree. In JSCH to list files using :
Vector list = channelSftp.ls(path);
But i need that lists as java.io.File type. So i can get absolutePath and fileName, And i don't know how to retrieve as java.io.File type.
Here is my code, and i try it work for local directory.
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
}
}
}
Please help me, thanks before :)
回答1:
you can define some variable in your java bean like
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
in JSCH you can absolute path using ChannelSftp#realpath but unfortunately there no way to get Exact file with extension .But you can use something like this to check whether that file name existed in the target directory or not.
SftpATTRS sftpATTRS = null;
Boolean fileExists = true;
try {
sftpATTRS = channelSftp.lstat(path+"/"+"filename.*");
} catch (Exception ex) {
fileExists = false;
}
回答2:
Try this (linux in remote server):
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
}
}
}
}
After you can invoque this method as:
DefaultMutableTreeNode nroot = new DefaultMutableTreeNode(sshremotedir);
try {
cargarRTree(sshremotedir, nroot);
} catch (SftpException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
yourJTree = new JTree(nroot);
来源:https://stackoverflow.com/questions/15061852/display-remote-directory-all-files-in-jtree