skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

  • Home
 
  • RSS
  • Twitter
Showing posts with label FTP Example. Show all posts
Showing posts with label FTP Example. Show all posts
Sunday, October 14, 2012

FTP CLIENT SERVER COMMUNICATION

Posted by Raju Gupta at 8:00 PM – 0 comments
 

This is an implementation of FTP Client Server interaction written in JAVA. It is a widely used protocol for remote file access.

Most of the Programmer need to work on remote Client Network.And so they will be needing to access remote files. File Transfer Protocol will help them to access remote files.This snippet can help them understand how its implemented in JAVA.   

//FtpClient.java

import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
class FtpClient extends JFrame implements ActionListener
{
 String fn,filenm;
 String fc;
 String dirn="c:/FTP CLIENT DIRECTORY";
 JPanel pnl;
 JLabel lbltle,lblud;
 Font fnt;
 JTextField txtfn;
 JButton btnu,btnd;
 Socket s;
 InputStreamReader in;
 OutputStream out;
 BufferedReader br;
 PrintWriter pw;
 public FtpClient()
 {
  super("FTP CLIENT");

  pnl=new JPanel(null);

  fnt=new Font("Times New Roman",Font.BOLD,25);

  lbltle=new JLabel("FTP CLIENT");
  lbltle.setFont(fnt);
  lbltle.setBounds(225,35,200,30);
  pnl.add(lbltle);

  lblud=new JLabel("ENTER  FILE-NAME :");
  lblud.setBounds(100,100,150,35);
  pnl.add(lblud);

  txtfn=new JTextField();
  txtfn.setBounds(300,100,200,25);
  pnl.add(txtfn);

  btnu=new JButton("UPLOAD");
  btnu.setBounds(150,200,120,35);
  pnl.add(btnu);


  btnd=new JButton("DOWNLOAD");
  btnd.setBounds(320,200,120,35);

  pnl.add(btnd);

  btnu.addActionListener(this);
  btnd.addActionListener(this);
  getContentPane().add(pnl);

  try
  {
   s=new Socket("localhost",100);
   br=new BufferedReader(new InputStreamReader(s.getInputStream()));
   pw=new PrintWriter(s.getOutputStream(),true);
   out=s.getOutputStream();
  }
  catch(Exception e)
  {
   System.out.println("ExCEPTION :"+e.getMessage());
  }
 }
 public void actionPerformed(ActionEvent e)
 {
  if(e.getSource()==btnu)
  {
   try
   {
    filenm=txtfn.getText();
    pw.println(filenm);
    FileInputStream  fis=new FileInputStream(filenm);
    byte[] buffer=new byte[1024];
    int bytes=0;

    while((bytes=fis.read(buffer))!=-1)
    {
     out.write(buffer,0,bytes);
    }
    fis.close();
   }
   catch(Exception exx)
   {
    System.out.println(exx.getMessage());
   }
  }

  if(e.getSource()==btnd)
  {
   try
   {
    File dir=new File(dirn);
    if(!dir.exists())
    {
     dir.mkdir();
    }
    else{}
    boolean done=true;
    filenm=txtfn.getText();
    fn=new String("#"+filenm+"#");
    //System.out.println(filenm);
    pw.println(fn);
    File f=new File(dir,filenm);
    FileOutputStream fos=new FileOutputStream(f);
    DataOutputStream dops=new DataOutputStream(fos);
    while(done)
    {
     fc=br.readLine();
     if(fc==null)
     {
      done=false;
     }
     else
     {
      dops.writeChars(fc);
      //  System.out.println(fc);

     }
    }
    fos.close();
   }

   catch(Exception exx)
   {}

  }
 }
 public static void main(String args[])
 {
  FtpClient ftpc=new FtpClient();
  ftpc.setSize(600,300);
  ftpc.show();
 }
}



//FtpServer.java
import java.io.*;
import java.net.*;

public class FtpServer
{
 public static void main(String [] args)
 {
  int i=1;

  System.out.println("******************************************************
    **************************");
    System.out.println("******************************   FTP 
      SERVER
      ***********************************");

      System.out.println("******************************************************
        **************************");
        System.out.println("Server Started...");
        System.out.println("Waiting for connections...");
        System.out.println("
          ");
          try
          {

           ServerSocket s = new ServerSocket(100);
           for(;;)
           {
            Socket incoming = s.accept();
            System.out.println("New Client Connected with id " 
              + i
              +" from "+incoming.getInetAddress().getHostName()+"..." );
            Thread t = new ThreadedServer(incoming,i);
            i++;
            t.start();
           }
          }
          catch(Exception e)
          {
           System.out.println("Error: " + e);
          }
 }
}

class ThreadedServer extends Thread
{
 int n;
 String c,fn,fc;
 String filenm;
 Socket incoming;
 int counter;
 String dirn="c:/FTP SERVER DIRECTORY";
 public ThreadedServer(Socket i,int c)
 {
  incoming=i;
  counter=c;
 }

 public void run()
 {
  try
  {

   BufferedReader in =new BufferedReader(new
     InputStreamReader(incoming.getInputStream()));
   PrintWriter out = new
     PrintWriter(incoming.getOutputStream(), true);
   OutputStream output=incoming.getOutputStream();
   fn=in.readLine();
   c=fn.substring(0,1);

   if(c.equals("#"))
   {
    n=fn.lastIndexOf("#");
    filenm=fn.substring(1,n);
    FileInputStream fis=null;
    boolean filexists=true;
    System.out.println("Request to download file "+filenm+"
      recieved from "+incoming.getInetAddress().getHostName()+"...");
      try
    {
       fis=new FileInputStream(filenm);
    }
    catch(FileNotFoundException exc)
    {
     filexists=false;
     System.out.println("FileNotFoundException:
      "+exc.getMessage());
    }
    if(filexists)
    {
     sendBytes(fis, output) ;
     fis.close();
    }
   }
   else
   {
    try
    {
     boolean done=true;
     System.out.println("Request to upload file " +fn+"
       recieved from "+incoming.getInetAddress().getHostName()+"...");

       File dir=new File(dirn);
     if(!dir.exists())
     {
      dir.mkdir();
     }
     else
     {}
     File f=new File(dir,fn);
     FileOutputStream fos=new FileOutputStream(f);
     DataOutputStream dops=new DataOutputStream(fos);

     while(done)
     {
      fc=in.readLine();
      if(fc==null)
      {
       done=false;
      }
      else
      {
       dops.writeChars(fc);
       // System.out.println(fc);

      }
     }
     fos.close();
    }
    catch(Exception ecc)
    {
     System.out.println(ecc.getMessage());
    }
   }
   incoming.close();
  }
  catch(Exception e)
  {
   System.out.println("Error: " + e);
  }
 }
 private static void sendBytes(FileInputStream f,OutputStream op)
   throws Exception
   {
  byte[] buffer=new byte[1024];
  int bytes=0;

  while((bytes=f.read(buffer))!=-1)
  {
   op.write(buffer,0,bytes);
  }
   }
}



[ Read More ]
Read more...
Saturday, October 13, 2012

Secure File Transfer using java Program

Posted by Raju Gupta at 8:00 PM – 0 comments
 

This program provides transfer of all files from source directory to destination directory securely.
To compile and run this program , one should have the jars edtftpj-pro-3.1.2.jar and edtftpj-pro-license.jar handy.

How to compile :

javac -classpath $CLASSPATH:edtftpj-pro-3.1.2.jar:edtftpj-pro-license.jar secureMultipleFileTransfer.java

How to run :

1)export CLASSPATH=$CLASSPATH:edtftpj-pro-3.1.2.jar:edtftpj-pro-license.jar

2)java secureMultipleFileTransfer   

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import com.enterprisedt.net.ftp.FTPException;
import com.enterprisedt.net.ftp.FTPFile;
import com.enterprisedt.net.ftp.Protocol;
import com.enterprisedt.net.ftp.SecureFileTransferClient;
import java.io.FileReader;
import com.enterprisedt.net.ftp.FTPTransferType;


public class secureMultipleFileTransfer {

    public secureMultipleFileTransfer() {
               
    }
    
    public static void main(String[] args) throws FTPException { 
        boolean isRecursive = false;      
 SecureFileTransferClient sftp = new SecureFileTransferClient();
        String srcDirName = "/home/test/src/";          
        String destDirectory="/home/test/dest/";
   
 try { 
       File dir = new File(srcDirName);
       if(dir.exists()) {       
          String [] FileName = dir.list();
          if (null != FileName) {
           System.out.println("Number of files in source directory ** "+FileName.length);
           }         
                 System.out.println("Set host name to connect***");
          sftp.setRemoteHost("Test.Server");
   System.out.println("Set User name***");
          sftp.setUserName("abcd");
   System.out.println("Set Password***");
          sftp.setPassword("test123");
          sftp.setProtocol(Protocol.SFTP);
          Protocol p = sftp.getProtocol();      
          System.out.println("Connecting to the host*** ");          
          sftp.connect();
   System.out.println("Connected to the host*** ");
   System.out.println("Setting the mode of transfer of file*** ");      
                 sftp.setContentType(FTPTransferType.BINARY);                        
   System.out.println("Trasferring file from source to destination***");
          sftp.uploadMultiple(srcDirName,destDirectory,"*",isRecursive);
   System.out.println("Files transferred successfully***");
              }
 } catch (FileNotFoundException fe){
     fe.printStackTrace();
     System.exit(1);
 } catch (Exception ex){      
     String errorMsg = "Caught Exception ";
     System.out.println(errorMsg); 
            ex.printStackTrace();                 
  } finally{
      try{
          sftp.disconnect();  
        
      } catch (Exception ex) {      
          String errorMsg = "Caught Exception ";
          System.out.println(errorMsg); 
                 ex.printStackTrace();                 
      }
        
         }
    }
}


[ Read More ]
Read more...
Older Posts
Subscribe to: Posts ( Atom )

List of Java Programs

  • Java Program to check Greater between the Two Number
  • Java Program to find that given number is Palindrome or not
  • Java Program to Demonstrate the Use of Pre and Post Operator
  • Java Program to Reverse the Given Number
  • Java Program to Print Number in the Given Data Type
  • Program to Demonstrate Skipping using Continue
  • Program to find whether entered character is a vowel or Consonant
  • Java Program to Calculate the Sum of Digits of Given Number
  • How to swap two numbers using only two variables
  • Checking the Given Number is Armstrong or Not
  • Average an Array of Values
  • Display ASCII Code Instead of Character
  • Comparison of Two Variable using If
  • Printing Table In java using While Loop
  • Generate Random Number Using Math.Random Function
  • To Find roots of Quadratic Equation
  • Performing Arithmetic Opration on Two Variable
  • Concatenation of Two String in Java
  • Command Line Argument in JAVA
  • Java Hello World Program
  • Calculate Circle Perimeter | Java Program
  • Calculate the Area of Circle | Java Program
  • To Find Whether Given Year is a Leap Year or not
  • Popular
  • Recent
  • Archives

Total Pageviews

Sparkline

Followers

Popular Posts of This Week

Powered by Blogger.

Archives

  • ▼  2014 ( 4 )
    • ▼  August ( 4 )
      • Java program to create a Binary Heap and Perform v...
      • Create an Adjacency matrix Graph and perform Add a...
      • To Sort an Interger Array using Shell Sort
      • Sort an Integer array with Bucket Sort
  • ►  2013 ( 6 )
    • ►  August ( 1 )
    • ►  April ( 5 )
  • ►  2012 ( 673 )
    • ►  November ( 9 )
    • ►  October ( 223 )
    • ►  September ( 272 )
    • ►  August ( 2 )
    • ►  June ( 1 )
    • ►  February ( 67 )
    • ►  January ( 99 )
 

Our Blogs

  • Linux Tutorial
  • C Programming Tutorial

Labels

  • Agile Methodology ( 1 )
  • Algorithm ( 3 )
  • AntiSamy ( 1 )
  • Arithmetic Operation ( 1 )
  • Array Example ( 9 )
  • ArrayList Examples ( 11 )
  • Average an Array of Values ( 1 )
  • Barcode Example ( 1 )
  • Basic Java Programs ( 34 )
  • Bing API Example ( 2 )
  • BitSet Example ( 1 )
  • Boolean Example ( 1 )
  • Bouncy Castle API ( 1 )
  • Break Statement ( 2 )
  • BufferedReader Example ( 2 )
  • Calendar Example ( 1 )
  • Chart Generation Example ( 1 )
  • Command Line Argument ( 1 )
  • Comparator Example ( 1 )
  • Concatenation of String ( 1 )
  • Continue Statement ( 1 )
  • Control Structure ( 1 )
  • Copy File Example ( 1 )
  • CRC Example ( 1 )
  • CSV Example ( 6 )
  • Data Structure ( 5 )
  • Date Example ( 2 )
  • Directory Example ( 1 )
  • Do - While Loop Example ( 1 )
  • Domino Database ( 1 )
  • Email Example ( 8 )
  • Encryption Example ( 3 )
  • Excel Example ( 15 )
  • Factorial Example ( 1 )
  • File Upload Example ( 1 )
  • Find Roots of Quadratic Equation ( 1 )
  • FTP Example ( 2 )
  • Graph Examples ( 1 )
  • Greater between Two Numbers ( 1 )
  • GSON Library ( 1 )
  • HashMap Example ( 1 )
  • HashSet Example ( 1 )
  • Hello World Program ( 1 )
  • If Condition ( 2 )
  • Inner Class Example ( 1 )
  • iText Example ( 3 )
  • JAR File ( 1 )
  • JAVA Applet ( 1 )
  • Java Applications ( 1 )
  • Java AWT Example ( 9 )
  • Java Certification ( 1 )
  • Java Class Examples ( 15 )
  • Java Collection Example ( 1 )
  • Java Command Example ( 4 )
  • Java Constructor Examples ( 1 )
  • Java Currency Example ( 1 )
  • Java Database Example ( 3 )
  • Java Date and Time Example ( 3 )
  • Java DateFormat Example ( 3 )
  • Java Examples ( 2 )
  • Java Exception Example ( 5 )
  • Java File Example ( 22 )
  • Java GUI Example ( 1 )
  • Java Image Examle ( 3 )
  • Java Inheritance Example ( 3 )
  • Java Input Output Example ( 1 )
  • Java IO Example ( 3 )
  • Java Jar Example ( 1 )
  • Java JSON Example ( 3 )
  • Java Mail Examples ( 4 )
  • Java Map Example ( 5 )
  • Java MapReduce Example ( 2 )
  • Java MultiThreading Example ( 7 )
  • Java Network Example ( 9 )
  • Java Package ( 1 )
  • Java Programs ( 1 )
  • Java RMI ( 1 )
  • Java Robot Class Examples ( 2 )
  • Java Runtime Example ( 1 )
  • Java Swing Example ( 9 )
  • Java Util Example ( 1 )
  • Java Vector Example ( 4 )
  • Java Voice Example ( 1 )
  • Java Webservice Example ( 1 )
  • Java XML Example ( 3 )
  • Java Zip Class Examples ( 2 )
  • JDBC ( 9 )
  • JDK Version Comparison ( 1 )
  • JFrame Example ( 3 )
  • JOptionPane Dialog Example ( 1 )
  • JPanel Example ( 1 )
  • JSP Example ( 2 )
  • JSTL Example ( 1 )
  • jUnit Example ( 2 )
  • LinkedList Example ( 2 )
  • List Example ( 1 )
  • Long Variable ( 1 )
  • Lottery Nubmer ( 1 )
  • MD5 Hashing Example ( 3 )
  • Memory Management Example ( 1 )
  • Method Override ( 1 )
  • MIDI Sound ( 8 )
  • Module Operator Example ( 2 )
  • Multiplication Table ( 1 )
  • Observer Interface Example ( 1 )
  • Operator Example ( 5 )
  • Pagination ( 1 )
  • Palindrome Number ( 1 )
  • Pass By Reference Example ( 1 )
  • Pass By Value Example ( 1 )
  • PDF File Example ( 3 )
  • PDF Generation Example ( 4 )
  • Pre and Post Operator ( 2 )
  • Prime Number ( 3 )
  • Progress Bar Example ( 1 )
  • Property List Example ( 2 )
  • Random Function ( 7 )
  • Recursion Example ( 2 )
  • Regex Example ( 2 )
  • Remote Host Example ( 2 )
  • Robot Class ( 4 )
  • Searching Example ( 3 )
  • Slideshow ( 1 )
  • Sorting Example ( 7 )
  • SpringLayout Example ( 1 )
  • Stack Example ( 4 )
  • Static Variable ( 1 )
  • StreamTokenizer Example ( 2 )
  • String Example ( 19 )
  • Struts2 Example ( 1 )
  • Sum of Digits ( 1 )
  • Swap Two Numbers ( 1 )
  • Switch Case ( 3 )
  • Tapestry Components ( 1 )
  • Thumbnail Example ( 2 )
  • TimerTask Example ( 2 )
  • To Calculate Volume ( 1 )
  • To Check Armstrong Number ( 1 )
  • Tree Example ( 1 )
  • TreeMap Example ( 1 )
  • TreeSet Example ( 1 )
  • Two Dimensional Array Example ( 1 )
  • UUID ( 1 )
  • Validation Example ( 2 )
  • Variable Casting ( 1 )
  • While Loop ( 1 )
  • XML Parsing ( 7 )
  • XSS Attacks ( 1 )
  • Zip File ( 15 )

Popular Posts

 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger