How do I use the nonstandard sun.net.ftp.FtpClient class to FTP a file from a server?

John Zukowski

While this class is completely unsupported and it may not be available on a user's runtime, you can use it when available. The following program demonstrates its usage. For some reason the closeServer() call doesn't return with JDK 1.3 so is commented out.

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

public class FtpExample {

  public static void main(String args[]) throws Exception {

    FtpClient fc;

    String host = args[0];
    String path = args[1];
    String username = args[2];
    String password = args[3];

    int lastSlash = path.lastIndexOf('/');
    String filename = path.substring(lastSlash+1);
    String directory = path.substring(0,lastSlash);

    FtpClient client = new FtpClient(host);
    client.login(username, password);
    client.binary();
    client.cd(directory);

    InputStream is = client.get(filename);
    BufferedInputStream bis = new BufferedInputStream(is);

    OutputStream os = new FileOutputStream(filename);
    BufferedOutputStream bos = new BufferedOutputStream(os);

    byte[] buffer = new byte[1024];
    int readCount;

    System.out.println("Getting: " + filename);
                    
    while( (readCount = bis.read(buffer)) > 0) {
      bos.write(buffer, 0, readCount);
    }
    bos.close();
//    client.closeServer();
  }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact