FtpClient文件的下载

来源:互联网 发布:dvp_60es编程 编辑:程序博客网 时间:2024/05/22 09:38
package wingsoft.ftp.download;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import sun.net.ftp.FtpClient;
import sun.net.ftp.FtpProtocolException;
public class Ftp {
 private FtpClient ftpClient;
 
 /*
  * 链接ftp
  * @path:ftp子目录
  */
 public void conn(String ip,int port,String user,String pwd,String path){
  try {
   ftpClient=FtpClient.create();
   ftpClient.connect(new InetSocketAddress(ip,port));
   ftpClient.login(user, pwd.toCharArray());
   System.out.println("login success!");
   if(path.length()!=0){
    ftpClient.changeDirectory(path);
   }
  } catch (FtpProtocolException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 /*
  * 关闭链接
  */
 public void closeFTP(){
  try {
   ftpClient.close();
   System.out.println("关闭ftp链接");
  } catch (IOException e) {
   System.out.println("ftp链接,关闭失败");
   e.printStackTrace();
  }
 }
 
 /*
  * 从ftp上下载文件到本地
  * @param ftpFile  读取的文件名如:1.test
  * @param localFile 下载到本地的文件
  */
 public long download(String ftpFile,String localFile) {
  InputStream is = null;
  FileOutputStream os = null;
  long result = 0;
  
  //读取文件
  try {
   is = ftpClient.getFileStream(ftpFile);
   java.io.File outfile = new java.io.File(localFile);
   os = new FileOutputStream(outfile);
  } catch (FtpProtocolException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  //byte[]
  byte[] buffer = new byte[1024];
  int c;
  try {
   while((c = is.read(buffer)) != -1){
    result = result +c;
    os.write(buffer, 0, c);
   }
  } catch (IOException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
  
  //关闭
  if(is !=null){
   try {
    is.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  if(os!=null){
   try {
    os.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  return result;
  
 }
  
 
 public static void main(String[] args) {
  Ftp ftp = new Ftp();
  ftp.conn("127.0.0.1", 21, "admin", "123","/temp");
  ftp.download("\\temp\\del.jpg","D:\\downtest\\1.jpg");
  ftp.closeFTP();
 }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
}