skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Wednesday, September 19, 2012

String Search through FTP files

Posted by Admin at 9:43 AM – 0 comments
 

Searching for a string through number of files in an FTP folder manually is a cumbersome process especially when the number of files in the folder is huge. This is a sample code would search for a particular string in all files of a specific folder of FTP. The folder name can be changed in the code according to the requirement


import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

public class search_case {
 
public static void main(String[] args){
 
 try{
  FTPClient client = new FTPClient();
  OutputStream out = null;
  String host = "url of the FTP";
  String tempString;
  String searchId = "testString";
  int i;
        
  client.connect(host);   
  client.login("username", "password");   
  System.out.println("Connected");
  client.cwd("/home/username/foldername");
  FTPFile[] files = client.listFiles(); 
  int count = files.length;
  System.out.println("Total number of files "+count);
    
        for(i=0;i<files.length;i++)
        {
          
  String temp = files[i].toString();
      
  ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  client.retrieveFile(temp,baos);
  
  byte[] tempFile = baos.toByteArray();
  ByteArrayInputStream bais = new ByteArrayInputStream(tempFile);
  BufferedReader br = new BufferedReader (new InputStreamReader(bais));
     
  while((tempString=br.readLine())!=null){
   
          if(tempString.indexOf(searchId)!=-1){
           
           System.out.println("the search string -- "+searchId +" --is found in the file--"+temp);        
              
             
          }
                    
              }   
  br.close();   
        baos.close();
        bais.close();
  
    }
             
        
  }catch(Exception exception)
  {
   exception.printStackTrace();
  }
 
}


}


Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger