Link to home
Start Free TrialLog in
Avatar of berg1375
berg1375

asked on

Java and FTP

I am currently using FTP to pull text files down from a website. I am using a simple batch file, and FTP commands. I have created a Java applet and now want to use this Applet to pull the files down instead of the batch file. Can someone give me some tips, source code, whatever you think I may need to accomplish this task. I am just brushing up on my Java, so I am not very well versed.

Also, this the code is going to be pulling all files of a particular extension down from this site. So I suppose it would have to be able to be used on a loop, so I can pull all files until EOF.

This is the code I have for the applet that will run this FTP. It may not be the best code in the world, but it will work. What I want is for the code to FTP to run when the button in pressed. Will I need to reference a different .java file, or can I just reference a different a different function in this applets code?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class FTPTest
{
   private static String labelPrefix = "This application will pull files down from Bearware";
   
   public Component createComponents()
   {
      final JLabel label = new JLabel(labelPrefix);

      JButton button = new  JButton("Click me to start the download!");
      button.setMnemonic(KeyEvent.VK_C);
      button.addActionListener(new ActionListener()
      {
         public void actionPerformed(ActionEvent e)
         {}
      });

      JPanel pane = new JPanel();
      pane.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30));
      pane.setLayout(new GridLayout(0, 1));
      pane.add(button);
      pane.add(label);

      return pane;
   }

   public static void main(String[] args)
   {
      try
      {
         UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
      }  catch (Exception e) {}

      JFrame frame = new JFrame("FTP Bearware Files");
      FTPTest app = new FTPTest();
      Component contents = app.createComponents();
      frame.getContentPane().add(contents, BorderLayout.CENTER);

      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setVisible(true);
   }
}

...........................................................

This is the current string I use in the batch file:

Open Webname.com
user
pwrd
type binary
mget*.XXX
mdelete *.XXX

...........................................................

I need the connection to be able to do this type of string. Can I use a URL, what is the best way for me to go about this?

Thanks
berg
Avatar of berg1375
berg1375

ASKER

Okay, I have been looking through some source code for FTP in Java. It seems that his is a lot more complex then it has to be. What I want to do is first build a connection to this FTP site with Java, and then I can build from there. Can someone find me some source code for connecting to an FTP site with JAVA, and preferrably break it down so I can understand what is going on in it. I would like to learn this instead of just pasting code.

berg
ASKER CERTIFIED SOLUTION
Avatar of yongsing
yongsing

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
import java.io.*;
import sun.net.ftp.*;


public class FileFtp extends Thread {
   private Thread ftp = null;
   private String hostname;       //IP address or domain name of the remote host.
   private int portnum;           //FTP port number
   private String username;       //usercode we FTP from
   private String password;       //usercode's password
   private String filepath;       //Location if the file we will get from
   private String filename;       //File we will retrieve from
   private File destination;      //Local FTP socket instance.
   private int bufLen;            //Amount of data we get at one time
   private byte[] buffer;         //Place to strore retrieved data
   private FtpClient fc;          //Local FTP client instance.
   private FileOutputStream fos;  //Local file that will contain the file FTPed
   private InputStream is;        

 FileFtp(String host,int port, String user, String pass,String path, String file, String dir) {
   this.hostname = host;
   this.portnum = port;
   this.username = user;
   this.password = pass;
   this.buffer = new byte[Const.BUFFER_SIZE];
   this.bufLen = 0;
   this.filepath = path;
   this.filename = file;
   this.destination = new File(new StringBuffer(dir).append(this.filename).toString());
   this.ftp = new Thread(this);
   
   System.out.println(new StringBuffer("FTP Stack starting for: ").append(this.filepath).append("/").append(this.filename).toString());
   
   try {
       this.fc = new FtpClient(this.hostname, this.portnum);
       this.fc.login(this.username, this.password);
       this.fc.binary();
       this.fc.cd(this.filepath);
       //Offer a passive.  
       this.is = this.fc.get(this.filename);
       this.fos = new FileOutputStream(this.destination);
       if (this.ftp != null) {
           this.ftp.start();
       }
    } catch (FtpLoginException e) {
           System.out.println("Caught Error: Could not login to " + hostname +":" + portnum);
           this.stopFtp();            
       }
      catch (FtpProtocolException e) {
           System.out.println("Caught Error: Ftp Protocol Error in " + hostname +":" + portnum);
           this.stopFtp();            
       }
      catch (java.net.ConnectException e) {
           System.out.println("Caught Error: Could not connect to " + hostname +":" + portnum);
           this.stopFtp();            
       }
      catch (java.net.UnknownHostException e) {
           System.out.println("Caught Error: Unknown host " + hostname);
           this.stopFtp();            
       }
      catch (java.net.NoRouteToHostException e) {
           System.out.println("Caught Error: No route found to " + hostname);
           this.stopFtp();            
       }
      catch (java.io.FileNotFoundException e) {
           System.out.println("Caught Error: File not found for " + this.filepath + "/" + this.filename
+ " in FileFtp.download()");
           this.stopFtp();            
       }
      catch (java.io.IOException e) {
           System.out.println("Caught Error: IO Error in setting up FTP: " + String.valueOf(e));
           this.stopFtp();            
       }
       catch (NullPointerException e) {
           System.out.println("Caught Error: Null Error in fileFtp.Start():"+String.valueOf(e));  
           
           this.stopFtp();            
       }
       catch (Exception e) {
           System.out.println("Caught Error: Exception in FileFtp Start():"+String.valueOf(e));    
                 
           this.stopFtp();
       }
       
       finally {
       }
 }
 
 public boolean stopFtp() {
   if ( !(this.ftp == null) ) {
       this.is = null;
       this.fos = null;
       this.fc = null;
       this.ftp = null;
       return true;
   } else {
       this.is = null;
       this.fos = null;
       this.fc = null;
       return false;
   }
 }
 
 public void run() {
   Thread thisThread = Thread.currentThread();
   try {
    while (this.ftp == thisThread) {
       while ((this.bufLen = this.is.read(this.buffer)) > 0) {
              this.fos.write(this.buffer,0,this.bufLen);
              this.ftp.yield();
       }
       
       this.is.close();
       this.fos.close();
       this.fc.closeServer();
       this.stopFtp();
   
       System.out.println(new StringBuffer("FTP Complete for: ").append(this.filepath).append("/").append(this.filename).toString());
               
    }
   
    } catch (java.io.IOException e) {
       System.out.println("Caught Error: IO Error in downloading file:"+ this.filepath + "/" + this.filename);

       this.stopFtp();

    } catch (java.lang.NullPointerException e) {
       System.out.println("Caught Error: Null Error in fileFtp.Run():" + String.valueOf(e));
       this.stopFtp();        
    }
  }    
}

Regards

Sudhakar
Okay, if I can not run this code in an applet, how will I go about this? I need a GUI for the user to be able to run this download on demand. I work with very computer illiterate people, so they need GUI's.

Can you 2 also give me a breakdown of the important parts of your code? I want to understand what I am doing, not just cut and paste code.

Thanks
berg
It is not possible for your applet to communicate wtih other hosts, except the one it originates from. I've never really tried doing so, but that's what all the books say.
Well then, I suppose that I will have to find a different project to do in Java. Any ideas? Like I said I am looking for something meaning full, that will help me learn Java a little better.
Instead of an applet, why not just make it an application?

Another way of doing is to have a program, say a servlet, residing on the host where the applet is. The applet will have the GUI for the user. On request from the user, the applet will pass the requested file names to the servlet. The servlet, on getting the file names, will do the actual FTP to get the required files, and then pass them to the applet.
Sounds like a plan. I will try to get something together on thursday, then award points.
I am giong to have CS reduce the points of this Q to 50, since I was not able to do what I wanted. It is no ones fault but I think points need to be handed out, since I did get an answer, just not the one I wanted. Thanks to all.

berg
As requested

modder
Community Support Moderator@Experts-Exchange