Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Java and FTP

Posted on 2001-07-02
10
Medium Priority
?
520 Views
Last Modified: 2013-11-23
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
0
Comment
Question by:berg1375
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
10 Comments
 
LVL 4

Author Comment

by:berg1375
ID: 6245608
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
0
 
LVL 9

Accepted Solution

by:
yongsing earned 200 total points
ID: 6246836
I think you're out of luck. An applet cannot communicate with any host except the one that it is downloaded from.

If you're using an application, you can use the sun.* package which is secretly included in the JDK. Therefore, you don't have to write everything from scratch, or download any additional stuff. Here is a sample code on how to upload a file to the FTP server.

import java.io.*;
import java.util.*;
import java.net.*;
import sun.net.ftp.FtpClient;
import sun.net.TelnetOutputStream;

public class TestFTP {

       /** The host name of the FTP server. */
       private String host = "somename";

       /** The user ID to login to the FTP server. */
       private String userID = "user";

       /** The password to login to the FTP server. */
       private String password = "xxxxxx";

       /** The directory on the FTP server to upload files to. */
       private String directory = "filesdir";

       /** The name of the file you want to upload. */
       private String fileName = "somefile.doc";

        public static void main(String[] args) {
             try {
                FtpClient ftpClient = new FtpClient();
                ftpClient.openServer(host); // connect to FTP server
                ftpClient.login(userID, password); // login
                ftpClient.binary(); // set to binary mode transfer
                ftpClient.cd(directory); // change directory
                File file = new File(fileName);
                TelnetOutputStream out = ftpClient.put(file.getName());
                FileInputStream in = new FileInputStream(file);
                int c = 0;
                int total_bytes = 0;
                while ((c=in.read(bytes)) != -1 ) {
                    total_bytes += c;
                    out.write(bytes, 0, c);
                }
                in.close();
                out.close();
                ftpClient.closeServer();
            } catch (Exception exception) {
                exception.printStackTrace();
              }
        }

}

However, take note that the sun.* package is not guaranteed that it will be included in future versions of the JDK.
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 6247367
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
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 4

Author Comment

by:berg1375
ID: 6248390
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
0
 
LVL 9

Expert Comment

by:yongsing
ID: 6250917
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.
0
 
LVL 4

Author Comment

by:berg1375
ID: 6251010
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.
0
 
LVL 9

Expert Comment

by:yongsing
ID: 6251030
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.
0
 
LVL 4

Author Comment

by:berg1375
ID: 6251292
Sounds like a plan. I will try to get something together on thursday, then award points.
0
 
LVL 4

Author Comment

by:berg1375
ID: 6265011
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
0
 
LVL 3

Expert Comment

by:modder
ID: 6265036
As requested

modder
Community Support Moderator@Experts-Exchange
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses

610 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question