#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2013
    Posts
    7
    Rep Power
    0

    Cool FTP populate jtree with files & directories from server


    Am using Apache commons and am trying to show specified files and directories from a server,does anyone know how to do this,i cant find anyone who does on the internet...neither am i getting a sample code......someone please help .Thank you n advance
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2013
    Posts
    7
    Rep Power
    0
    this is the code i found so far and it seems not to work, can some please help me or am i alone on this and have to figure myself out

    Code:
    public String[] getDir(String rootDirectory) {         String server = "192.168.1.11";         int port = 21;         String user = "javaapp";         String pass = "nascalebio";         String Directory = "/cms";         String[] directories;          FTPClient ftpClient = new FTPClient();                  try {             ftpClient.connect(server, port);             ftpClient.login(user, pass);              FTPFile[] files = ftpClient.mlistDir(Directory);             directories = new String[files.length];             for (int i =0; i < files.length; i++) {                 directories[i] = files[i].getName();                 System.out.println(i);                 System.out.println(directories[i]);                 System.out.println(files.length);                }              return directories;          } catch (IOException e) {             System.out.println(e);         }         return null;             }      public void buildtree(String currentdir, DefaultMutableTreeNode model) throws SocketException, IOException {         String[] currentcrawl = getDir(currentdir);         for (String node : currentcrawl) {         DefaultMutableTreeNode currentnode = new DefaultMutableTreeNode(node);         buildtree(currentdir +"/" + node, currentnode);         model.add(currentnode);          }            buildtree(".", root);         tree.setModel(new DefaultTreeModel(root));
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2013
    Posts
    7
    Rep Power
    0
    Originally Posted by nascal3
    this is the code i found so far and it seems not to work, can some please help me or am i alone on this and have to figure myself out

    Code:
    public String[] getDir(String rootDirectory) {         String server = "192.168.1.11";         int port = 21;         String user = "javaapp";         String pass = "nascalebio";         String Directory = "/cms";         String[] directories;          FTPClient ftpClient = new FTPClient();                  try {             ftpClient.connect(server, port);             ftpClient.login(user, pass);              FTPFile[] files = ftpClient.mlistDir(Directory);             directories = new String[files.length];             for (int i =0; i < files.length; i++) {                 directories[i] = files[i].getName();                 System.out.println(i);                 System.out.println(directories[i]);                 System.out.println(files.length);                }              return directories;          } catch (IOException e) {             System.out.println(e);         }         return null;             }      public void buildtree(String currentdir, DefaultMutableTreeNode model) throws SocketException, IOException {         String[] currentcrawl = getDir(currentdir);         for (String node : currentcrawl) {         DefaultMutableTreeNode currentnode = new DefaultMutableTreeNode(node);         buildtree(currentdir +"/" + node, currentnode);         model.add(currentnode);          }            buildtree(".", root);         tree.setModel(new DefaultTreeModel(root));
    got this code from http://forums.devshed.com/java-help-9/jtree-ftp-file-browser-894260.html
  6. #4
  7. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jan 2004
    Location
    Mobile, Alabama
    Posts
    4,039
    Rep Power
    1288
    Are you required to use Apache Commons? Have you tried Jsch?
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2013
    Posts
    7
    Rep Power
    0
    Originally Posted by bullet
    Are you required to use Apache Commons? Have you tried Jsch?
    No i haven't is it better?, have not even heard of it
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2013
    Posts
    7
    Rep Power
    0
    Originally Posted by bullet
    Are you required to use Apache Commons? Have you tried Jsch?
    can you show me how to do that using Jsch but most preferably Apache commons if also possible
  12. #7
  13. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jan 2004
    Location
    Mobile, Alabama
    Posts
    4,039
    Rep Power
    1288
    What is happening when you run the code? Are you sure the server allows FTP?
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2013
    Posts
    7
    Rep Power
    0
    Originally Posted by bullet
    What is happening when you run the code? Are you sure the server allows FTP?
    The jtree is not generated but it rather just keeps requesting the file list from the FTP sever continuously in a loop and the loop does not stop till you cancel the program when you force it to logout of the FTP server in gives error of "pointer null"
  16. #9
  17. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2016
    Posts
    1
    Rep Power
    0
    Hi all because i was also looking for a solution, how to display a ftpserver in a JTree and i did not found code, i wrote it myself. I use apache commons.
    It is propably not the best code, i am beginner. There is still a problem. To show empty directories as folders and not as files i proof them if they contain ".".
    But folders also can have "." in their name, so if a folder has an "." in their name it will come to an error. When you have an alternate method tell me.
    Sorry for bad english. Here is my code:

    Code:
    	package aufgabe;
    	import java.awt.*;
    	import java.io.*;
    	import java.util.*;
    	import java.awt.event.*;
    	import javax.swing.*;
    	import javax.swing.tree.*;
    	import org.apache.commons.io.*;
    	import org.apache.commons.net.ftp.*;
    	
    
    	public class ftptree{
    		
    		static Hashtable hash;
    		static FTPFile name=new FTPFile ();
    		static int uhu=0;
    		static DefaultMutableTreeNode root=new DefaultMutableTreeNode("server");
    		static TreePath TreePath;
    		static DefaultTreeModel model2;
    		static JTree tree2;
    		static JFrame frame=new JFrame();
    		static Hashtable h=new Hashtable();
    	    static Hashtable parenthash=new Hashtable();
    		DefaultMutableTreeNode current;
    		String key;
    	    Container content;
    	    JScrollPane scrollPane ;
    
    		public static void main(String[] args) {
    		
    	     FTPClient ftpClient = new FTPClient();
    	     try {
    	         ftpClient.connect("localhost", 2121);
    	         int replyCode = ftpClient.getReplyCode();
    	         if (!FTPReply.isPositiveCompletion(replyCode)) {
    	           
    	             return;
    	         }
    	         boolean success = ftpClient.login("admin", "admin");
    	         if (!success) {
    	           
    	             return;
    	         }
    	           
    	         ftptree z=new ftptree();
    	      	     
    	         z.hash(ftpClient,"","",h);
    	         
    	         z.baum(ftpClient,hash,parenthash);
    	      			  
    	     } catch (IOException ex) {        
    	        
    	         ex.printStackTrace();
    	     } finally {
    	        
    	         try {
    	        	 
    	             if (ftpClient.isConnected()) {
    	                 ftpClient.logout();
    	                 ftpClient.disconnect();
    	             }
    	         } catch (IOException ex) {
    	             ex.printStackTrace();
    	         }	         
    	     }}
    		
         public  void hash(FTPClient ftpClient,String dirold,String dir,Hashtable hashold) throws IOException
    		{	    
    	    FTPFile[] subFiles=null;
    
    	   String dir2=dirold;
    	    
    	    if (!dir.equals("")) {
    	        dir2 += "/" + dir;       
    	    }
    	   
    		try {
    
    			subFiles = ftpClient.listFiles(dir2);
    								
    		} catch (IOException e) {
    			
    			e.printStackTrace();
    		}
    		catch (StackOverflowError e) {
    			
    			e.printStackTrace();
    		}
    
    	    	hash=hashold;
    	    
    	    	String u="0";
    			   	
    	    	for(int i=0; i<subFiles.length;i++){
    				    		
    				name=subFiles[i];
    		
    					 try{
    						 																
    						 if(name.isDirectory()){
    					 
    							 hash.put(dir2+"/"+subFiles[i].getName(),dir2+"/"+subFiles[i].getName());
    						 u=u+"1";
    						 }
    						 if(name.isFile())
    						 {						
    							 hash.put(dir2,dir2);
    						 }
    							
    					  }
    					  catch(ArrayIndexOutOfBoundsException e)
    					  {
    						 
    					  }
    					 hash(ftpClient,dir2,name.getName(),hash);				
    	    	}	
    		}
    		  
    		  public  void baum(FTPClient ftpClient,Hashtable hash,Hashtable parenthash) throws IOException
    		  { 
    		 	
    			 Set<String> keys = hash.keySet();
    			
    	   	   	 DefaultMutableTreeNode first=null;
    	 	 
    	 	     model2 =  new DefaultTreeModel(root,true);
    	 
    		 		 
    			 for(String key: keys)		
    			 {
    						          
    		      char s='/';
    		     
    		      try{
    		    	  int counter =0;
    		    	  
    		    	   for (int i=0;i<hash.get(key).toString().length();i++)
    		    	   { 
    		    		   String schl=hash.get(key).toString();
    		    	        if (schl.charAt(i)==s)
    		    	        	{counter++;
    		    	        	    	        	
    		    	        	}		    	             	        
    		    	   }
    		    	   if(counter==1)
    		        	{
    		    		 		    		 
    		    		   if(hash.get(key).toString().contains("."))
    		    		   { 
    		    			   first=new DefaultMutableTreeNode(hash.get(key),false);
    		    			   
    		    		   }
    		    		   else{
    		    			   first=new DefaultMutableTreeNode(hash.get(key));
    		    		   }
    		        	
    		        		 root.add(first);
    		        	        	
    		        		 parenthash.put(first.toString(), first);
    		        		
    		        	}}
    		    	   catch(NullPointerException e)
    			       {
    			    	   
    			       }
    			      catch(StringIndexOutOfBoundsException e2)
    			      {
    			    	  
    			      }}
    		      	      			    	  			
    			      parents(parenthash,root,first,tree2,model2);
    			     		    
    			      tree2 = new JTree(model2);
    		try{
    			 	
    		   content = frame.getContentPane();
    		   scrollPane = new JScrollPane(tree2);
    		   content.add(scrollPane, BorderLayout.CENTER);
    		
    	       frame.setSize(400,400);
    	       frame.setVisible(true);
    		     
    			 }
    			 catch(NullPointerException e)
    			 {
    				
    			 }}
    		  
    		  public void  parents(Hashtable parenthash,DefaultMutableTreeNode root,DefaultMutableTreeNode erst,JTree tree2,DefaultTreeModel model2)
    		  {  	      
    			  DefaultMutableTreeNode parent=null;
    			 			
    		    	  Hashtable par=new Hashtable();
    		    	 
    			      Set <String>keys2 = parenthash.keySet();
    					      
    			      Iterator<String> iter = hash.keySet().iterator();
    			      while (iter.hasNext())
    				  {   key = iter.next();
    			    									  		 
    			      char s='/';
    			     
    			      try{
    			    	  int counter =0;
    			    	  
    			    	  
    			    	   for (int i=0;i<hash.get(key).toString().length();i++)
    			    	   { 
    			    		   String schl=hash.get(key).toString();
    			    	        if (schl.charAt(i)==s)
    			    	        	{counter++;
    			    	        		    	        	
    			    	        	}	    	        	        
    			    	   }
    			      
    	        		for(String e:keys2)       		
    	        		{  
    	        		 parent=new DefaultMutableTreeNode(parenthash.get(e));
    	        			
    	            		 current=new DefaultMutableTreeNode(hash.get(key));
    	            			        			
    	                if(current.toString().contains("."))
    	            		 { current.setAllowsChildren(false);}
    	        				        		
    	        		String sub2=new String(current.toString().substring(1));       
    	        	    StringBuffer strBuf = new StringBuffer(sub2);
    	        	
    	        		String subb=null;
    	        			        			
    	        		for (int i = 0; i < 1; i++) 
    	        		{
    	                   subb = current.toString().substring(0, current.toString().lastIndexOf("/"));
    	                   
    	                } 
    	        		    
    	        		StringBuffer subbf= new StringBuffer (strBuf.substring(0,strBuf.toString().indexOf('/')));	        		        		 
    	             	
    	        		if(parenthash.get(e).toString().contains(subb))       			
    	        		{ 
    	    	    	        
    	        		try
    	        		{	 
    	        			parent=(DefaultMutableTreeNode) parenthash.get(e);    
    	        		  			
    	        				}
    	        		catch(ClassCastException e2)
    	        		{     		
    	        			
    	                        DefaultMutableTreeNode node = searchNode(subb);
    	        		        if (node != null) {
    	        		          TreeNode[] nodes = model2.getPathToRoot(node);
    	        		          TreePath path = new TreePath(nodes);
    	        		          parent=node;
    	        		          parent.add(current);
    	        			        		      
    	        		        } }	        	        	 
    	        	      if(uhu==0)
    	        	      {
    	        	    	
    	        	    		for (int i = 0; i < root.getChildCount(); ++i) 
    	            			{
    	            	  			TreeNode child =  root.getChildAt(i);
    	            	  		
    	            	  			if (child.toString().equals(parent)==false) {
    	            	  			
    	            	  			}
    	            	  			if(child.toString().equals(parent.toString())==true)
    	            	  			{
    	            	  			
    	            	  				parent.add(current);
    	            	  			}
    	            	  		}}
    	        	      else{      	    	  
    	      	    		if(parent.toString().equals(subb)){	      	    	
    	      	    		}
    	      	    		}      	     			
    	        		if(current.toString().contains(".")==false)
    	  
    	            		{	              	
    	            		par.put(current.toString(), current.toString());	            	      		
    	            		}
    	        			else{	        			
    	        			}
    	        		  	try{   	      		
    	                 		iter.remove();
    	            			}
    	            		catch(NoSuchElementException e4)
    	            		{                     		}
    	        		  	
    	        		}}       	       		
    	        	   }    			  		      
    		       catch(NullPointerException e)
    		       {	       }
    		      catch(StringIndexOutOfBoundsException e2)
    		      {	      }	
    			      
    			  }	         	
    		    	  parenthash.clear();	    	
    		    	  parenthash=(Hashtable) par.clone();	    
    		    	  if(parenthash.isEmpty()==false)
    		        {
    		    		  uhu++;   		    		
    		              parents(parenthash,root,erst,tree2,model2);		      
    		        }	     	  		    
    		  }
    		  
    		  public  DefaultMutableTreeNode searchNode(String nodeStr) {
    			    DefaultMutableTreeNode node = null;
    			    Enumeration e = root.breadthFirstEnumeration();
    			    while (e.hasMoreElements()) {
    			      node = (DefaultMutableTreeNode) e.nextElement();
    			      if (nodeStr.equals(node.getUserObject().toString())) {
    			    	 
    			    	 try{
    			    	  
    			    	 }
    			    	 catch(NoSuchElementException e5)
    			    	 {
    			    		 
    			    	 }
    			    	  return node;			       
    			      }
    			    }
    			    return null;
    			    }	}

IMN logo majestic logo threadwatch logo seochat tools logo