FTP实现客户端与服务器文件传输(二)

/*
以sun开头的class不是java里面的标准类,而是sun公司自己的的class,因此,他们位于rt.jar当中。因此,jdk源代码中没有提供源文件。但是,可以用诸如jad之类的反编译工具进行反编译。
实际上,基本原理就是利用Socket和ServerSocket来发送遵守FTP协议的消息,与FTP服务器进行交互。
主要用到这么几个类:
sun.net.ftp.FtpClient extends sun.net.TransferProtocolClient
sun.net.TransferProtocolClient extends sun.net.NetworkClient
sun.net.TelnetInputStream extends FilterInputStream
sun.net.TelnetOutputStream extends BufferedOutputStream
因为是使用被动模式,因此,客户端要去连接服务端,
在FtpClient的源代码的openDataConnection(String s)方法中有这么一句:
serversocket = new ServerSocket(0, 1);也就是客户端随便选择一个空闲端口。
也就是说,sun的FtpClient不支持主动模式。
*/

public class FtpUtils {

 /**

  * 向FTP服务器上传文件

  * 

  * @param ip

  *            FTP服务器ip e.g:192.168.8.22

  * @param port

  *            FTP服务器端口 

  * @param username

  *            FTP登录账号 

  * @param password

  *            FTP登录密码  

  * @param serverpath

  *            FTP服务器保存目录(相对路径) 默认缺省时指向主目录

  * @param file

  *            上传到FTP服务器上的文件的绝对路径 e.g: E:/log/log.txt OR E:/log/log.txt

  *            

  * @return 

  *      成功返回true,否则返回false

  */

 public boolean uploadFile(String ip, int port, String username,

   String password, String serverpath, String file) {

  // 初始表示上传失败

  boolean success = false;

  // 创建FTPClient对象

  FTPClient ftp = new FTPClient();

  ftp.setControlEncoding("UTF-8"); 

  try {

   int reply=0;

   // 连接FTP服务器

   // 如果采用默认端口,可以使用ftp.connect(ip)的方式直接连接FTP服务器

   ftp.connect(ip, port);

   // 登录ftp

   ftp.login(username, password);

   // 看返回的值是不是reply>=200&&reply<300 如果是,表示登陆成功

   reply = ftp.getReplyCode();

   // 以2开头的返回值就会为真

   if (!FTPReply.isPositiveCompletion(reply)) {

    ftp.disconnect();

    return success;

   }

   // 转到指定上传目录

   serverpath=gbkToIso8859(serverpath);

   ftp.changeWorkingDirectory(iso8859ToGbk(serverpath));

   

   checkPathExist(ftp,iso8859ToGbk(serverpath));

   

   //输入流

   InputStream input=null;

   try {

    file=gbkToIso8859(file);

    input = new FileInputStream(iso8859ToGbk(file));

   } catch (FileNotFoundException e) {

    e.printStackTrace();

   }

   // 将上传文件存储到指定目录

   file=iso8859ToGbk(file);

   flag=ftp.storeFile(iso8859ToGbk(serverpath)+"/"+iso8859ToGbk(getFilename(file)), input);

   // 关闭输入流

   input.close();

   // 退出ftp

   ftp.logout();

   } catch (IOException e) {

   e.printStackTrace();

  } finally {

   if (ftp.isConnected()) {

    try {

     ftp.disconnect();

    } catch (IOException ioe) {

    }

   }

  }

  return success;

 }

 /**

  * 从FTP服务器下载文件

  * 

  * @param ip

  *            FTP服务器ip e.g:192.168.8.22

  * @param port

  *            FTP服务器端口

  * @param username

  *            FTP登录账号

  * @param password

  *            FTP登录密码

  * @param serverpath

  *            FTP服务器上的相对路径 默认缺省时指向主目录

  * @param fileName

  *            要下载的文件名

  * @param localPath

  *            下载后保存到本地的路径 不含文件名

  * @return

  *      成功返回true,否则返回false

  */

 public boolean downFile(String ip, int port, String username,

   String password, String serverpath, String fileName,

   String localPath) {

  // 初始表示下载失败

  boolean success = false;

  // 创建FTPClient对象

  FTPClient ftp = new FTPClient();

  ftp.setControlEncoding("UTF-8"); 

  try {

   int reply;

   // 连接FTP服务器

   // 如果采用默认端口,可以使用ftp.connect(ip)的方式直接连接FTP服务器

   ftp.connect(ip, port);

   // 登录ftp

   ftp.login(username, password);

   reply = ftp.getReplyCode();

   if (!FTPReply.isPositiveCompletion(reply)) {

    ftp.disconnect();

    return success;

   } 

   // 转到指定下载目录

   serverpath=gbkToIso8859(serverpath);

   ftp.changeWorkingDirectory(this.iso8859ToGbk(serverpath));

   // 列出该目录下所有文件

   FTPFile[] fs = ftp.listFiles();

   fileName=this.gbkToIso8859(fileName);

   localPath=this.gbkToIso8859(localPath);

   

   // 遍历所有文件,找到指定的文件

   for (FTPFile f : fs) {

    if (f.getName().equals(iso8859ToGbk(fileName))) {

     // 根据绝对路径初始化文件

     File localFile = new File(iso8859ToGbk(localPath) + "/" + f.getName());

     File localFileDir = new File(iso8859ToGbk(localPath));

     //保存路径不存在时创建

     if(!localFileDir.exists()){

      localFileDir.mkdirs();

     }

     // 输出流

     OutputStream is = new FileOutputStream(localFile);

     // 下载文件

     flag=ftp.retrieveFile(f.getName(), is);

     is.close();

    }

   }

   // 退出ftp

   ftp.logout();

   } catch (IOException e) {

   e.printStackTrace();

  } finally {

   if (ftp.isConnected()) {

    try {

     ftp.disconnect();

    } catch (IOException ioe) {

    }

   }

  }

  return success;

 }

 /**

  *  

  * 查找指定目录是否存在  不存在创建目录

  * 

  * @param FTPClient 

  *    ftpClient 要检查的FTP服务器

  * @param String 

  *    filePath 要查找的目录 

  * @return 

  *    boolean:存在:true,不存在:false 

  * @throws IOException 

  */

 private  boolean checkPathExist(FTPClient ftpClient, String filePath)

   throws IOException {

  boolean existFlag = false;

  try {

   if (filePath != null && !filePath.equals("")) {

    if (filePath.indexOf("/") != -1) {

     int index = 0;

     while ((index = filePath.indexOf("/")) != -1) {

      if (!ftpClient.changeWorkingDirectory(filePath.substring(0,index))) {

       ftpClient.makeDirectory(filePath.substring(0,index));

      }

      ftpClient.changeWorkingDirectory(filePath.substring(0,index));

      filePath = filePath.substring(index + 1, filePath.length());

     }

     if (!filePath.equals("")) {

      if (!ftpClient.changeWorkingDirectory(filePath)) {

       ftpClient.makeDirectory(filePath);

      }

     }

    } 

    existFlag = true;

   }

  } catch (Exception e) {

   e.printStackTrace();

  }

  return existFlag;

 }

 /**

  * 根据绝对路径获得文件名

  * @param file

  *      文件绝对路径 e.g: e.g: E:/log/log.txt OR E://log//log.txt

  * @return

  *      转码后的文件名 

  */

 private String getFilename(String file){

  //文件名

  String filename="";

  if(file!=null&&!file.equals("")){

   file=file.replaceAll(Matcher.quoteReplacement("//"), "/");

   String[] strs=file.split("/");

   filename=strs[strs.length-1];

  }

  filename=gbkToIso8859(filename);//转码

  return filename;

 }

 /** 

  * 转码[ISO-8859-1 ->  GBK] 

  * 不同的平台需要不同的转码 

  * @param obj 

  * @return 

  */

 private  String iso8859ToGbk(Object obj) {

  try {

   if (obj == null)

    return "";

   else

    return new String(obj.toString().getBytes("iso-8859-1"), "GBK");

  } catch (Exception e) {

   return "";

  }

 }

 /** 

  * 转码[GBK ->  ISO-8859-1] 

  * 不同的平台需要不同的转码 

  * @param obj 

  * @return 

  */

 private  String gbkToIso8859(Object obj) {

  try {

   if (obj == null)

    return "";

   else

    return new String(obj.toString().getBytes("GBK"), "iso-8859-1");

  } catch (Exception e) {

   return "";

  }

 }

代码说明:

向FTP服务器上传文件时调用uploadFile()方法,从FTP服务器下载文件时调用downFile()方法。

 

当然,想向FTP服务器上传文件,FTP服务器需要开写入权限。

 

需要用的jar是commons-net-2.0.jar。

猜你喜欢

转载自starbhhc.iteye.com/blog/2315883