Ftp学习

主Activity: FTPMainActivity

  1. <span style="font-size:14px; color:#000000">package com.example.ftpdemo;  
  2.   
  3. import android.os.Bundle;  
  4. import android.os.StrictMode;  
  5. import android.app.Activity;  
  6. import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;  
  7. import android.view.Menu;  
  8. import android.view.View;  
  9. import android.view.View.OnClickListener;  
  10. import android.widget.Button;  
  11. import android.widget.Toast;  
  12.   
  13. /** 
  14.  * 2013年09月20日21:28:51 测试demo 
  15.  *  
  16.  * 1.文件上传到FTP服务器  
  17.  * 2.从FTP服务器上下载文件 
  18.  *  
  19.  * 所需jar包:commons-net-3.0.1.jar 
  20.  * 将commons-net-3.0.1.jar放于libs中 
  21.  *  
  22.  * @author xiaoyaomeng 
  23.  *  
  24.  */  
  25. public class FTPMainActivity extends Activity implements OnClickListener {  
  26.   
  27.     //傻逼Buttons  
  28.     private Button buttonUpLoad = null;  
  29.     private Button buttonDownLoad = null;  
  30.       
  31.     //FTP工具类  
  32.     private FTPUtils ftpUtils = null;  
  33.       
  34.     @Override  
  35.     protected void onCreate(Bundle savedInstanceState) {  
  36.         super.onCreate(savedInstanceState);  
  37.         setContentView(R.layout.activity_ftpmain);  
  38.           
  39.         //获取控件对象  
  40.         buttonUpLoad = (Button) findViewById(R.id.button_upload);  
  41.         buttonDownLoad = (Button) findViewById(R.id.button_download);  
  42.   
  43.         //设置控件对应相应函数  
  44.         buttonUpLoad.setOnClickListener(this);  
  45.         buttonDownLoad.setOnClickListener(this);  
  46.           
  47.         if (android.os.Build.VERSION.SDK_INT > 9) {  
  48.             StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();  
  49.             StrictMode.setThreadPolicy(policy);  
  50.         }  
  51.           
  52.         //初始化和FTP服务器交互的类  
  53.         InitFTPServerSetting();  
  54.     }  
  55.   
  56.     public void InitFTPServerSetting() {  
  57.         // TODO Auto-generated method stub  
  58.         ftpUtils = FTPUtils.getInstance();  
  59.         boolean flag = ftpUtils.initFTPSetting("chenww.3vfree.us"21"chenww""chenww");  
  60.               
  61.     }  
  62.   
  63.     @Override  
  64.     public boolean onCreateOptionsMenu(Menu menu) {  
  65.         // Inflate the menu; this adds items to the action bar if it is present.  
  66.         getMenuInflater().inflate(R.menu.ftpmain, menu);  
  67.         return true;  
  68.     }  
  69.   
  70.     @Override  
  71.     public void onClick(View v) {  
  72.         // TODO Auto-generated method stub  
  73.         switch (v.getId()) {  
  74.                             case R.id.button_upload: {  
  75.                                 //上传文件  
  76.                                   
  77.                             }  
  78.                                 break;  
  79.                             case R.id.button_download: {  
  80.                                 //下载文件  
  81.                                   
  82.                             }  
  83.                                 break;  
  84.                             default:  
  85.                                 break;  
  86.                       
  87.             }  
  88.     }  
  89. }</span> 



工具类:FTPUtils


  1. <strong><span style="font-size:14px">package com.example.ftpdemo;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.io.OutputStream;  
  8. import java.net.SocketException;  
  9.   
  10. import org.apache.commons.net.ftp.FTP;  
  11. import org.apache.commons.net.ftp.FTPClient;  
  12. import org.apache.commons.net.ftp.FTPFile;  
  13. import org.apache.commons.net.ftp.FTPReply;  
  14.   
  15. import android.R.bool;  
  16.   
  17. /** 
  18.  * 2013年09月20日21:38:04 
  19.  *  
  20.  * 用于Android和FTP服务器进行交互的工具类 
  21.  *  
  22.  * @author xiaoyaomeng 
  23.  * 
  24.  */  
  25. public class FTPUtils {  
  26.     private FTPClient ftpClient = null;  
  27.     private static FTPUtils ftpUtilsInstance = null;  
  28.     private String FTPUrl;  
  29.     private int FTPPort;  
  30.     private String UserName;  
  31.     private String UserPassword;  
  32.       
  33.     private FTPUtils()  
  34.     {  
  35.         ftpClient = new FTPClient();  
  36.     }  
  37.     /* 
  38.      * 得到类对象实例(因为只能有一个这样的类对象,所以用单例模式) 
  39.      */  
  40.     public  static FTPUtils getInstance() {  
  41.         if (ftpUtilsInstance == null)  
  42.         {  
  43.             ftpUtilsInstance = new FTPUtils();  
  44.         }  
  45.         return ftpUtilsInstance;  
  46.     }  
  47.       
  48.     /** 
  49.      * 设置FTP服务器 
  50.      * @param FTPUrl   FTP服务器ip地址 
  51.      * @param FTPPort   FTP服务器端口号 
  52.      * @param UserName    登陆FTP服务器的账号 
  53.      * @param UserPassword    登陆FTP服务器的密码 
  54.      * @return 
  55.      */  
  56.     public boolean initFTPSetting(String FTPUrl, int FTPPort, String UserName, String UserPassword)  
  57.     {     
  58.         this.FTPUrl = FTPUrl;  
  59.         this.FTPPort = FTPPort;  
  60.         this.UserName = UserName;  
  61.         this.UserPassword = UserPassword;  
  62.           
  63.         int reply;  
  64.           
  65.         try {  
  66.             //1.要连接的FTP服务器Url,Port  
  67.             ftpClient.connect(FTPUrl, FTPPort);  
  68.               
  69.             //2.登陆FTP服务器  
  70.             ftpClient.login(UserName, UserPassword);  
  71.               
  72.             //3.看返回的值是不是230,如果是,表示登陆成功  
  73.             reply = ftpClient.getReplyCode();  
  74.           
  75.             if (!FTPReply.isPositiveCompletion(reply))  
  76.             {  
  77.                 //断开  
  78.                 ftpClient.disconnect();  
  79.                 return false;  
  80.             }  
  81.               
  82.             return true;  
  83.               
  84.         } catch (SocketException e) {  
  85.             // TODO Auto-generated catch block  
  86.             e.printStackTrace();  
  87.             return false;  
  88.         } catch (IOException e) {  
  89.             // TODO Auto-generated catch block  
  90.             e.printStackTrace();  
  91.             return false;  
  92.         }  
  93.     }  
  94.       
  95.     /** 
  96.      * 上传文件 
  97.      * @param FilePath    要上传文件所在SDCard的路径 
  98.      * @param FileName    要上传的文件的文件名(如:Sim唯一标识码) 
  99.      * @return    true为成功,false为失败 
  100.      */  
  101.     public boolean uploadFile(String FilePath, String FileName) {  
  102.           
  103.         if (!ftpClient.isConnected())  
  104.         {  
  105.             if (!initFTPSetting(FTPUrl,  FTPPort,  UserName,  UserPassword))  
  106.             {  
  107.                 return false;  
  108.             }  
  109.         }  
  110.           
  111.         try {  
  112.               
  113.             //设置存储路径  
  114.             ftpClient.makeDirectory("/data");  
  115.             ftpClient.changeWorkingDirectory("/data");  
  116.               
  117.             //设置上传文件需要的一些基本信息  
  118.             ftpClient.setBufferSize(1024);    
  119.             ftpClient.setControlEncoding("UTF-8");   
  120.             ftpClient.enterLocalPassiveMode();     
  121.             ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  
  122.               
  123.             //文件上传吧~  
  124.             FileInputStream fileInputStream = new FileInputStream(FilePath);  
  125.             ftpClient.storeFile(FileName, fileInputStream);  
  126.               
  127.             //关闭文件流  
  128.             fileInputStream.close();  
  129.               
  130.             //退出登陆FTP,关闭ftpCLient的连接  
  131.             ftpClient.logout();  
  132.             ftpClient.disconnect();  
  133.               
  134.         } catch (IOException e) {  
  135.             // TODO Auto-generated catch block  
  136.             e.printStackTrace();  
  137.             return false;  
  138.         }  
  139.         return true;  
  140.     }  
  141.       
  142.     /** 
  143.      * 下载文件 
  144.      * @param FilePath  要存放的文件的路径 
  145.      * @param FileName   远程FTP服务器上的那个文件的名字 
  146.      * @return   true为成功,false为失败 
  147.      */  
  148.     public boolean downLoadFile(String FilePath, String FileName) {  
  149.           
  150.         if (!ftpClient.isConnected())  
  151.         {  
  152.             if (!initFTPSetting(FTPUrl,  FTPPort,  UserName,  UserPassword))  
  153.             {  
  154.                 return false;  
  155.             }  
  156.         }  
  157.            
  158.         try {  
  159.             // 转到指定下载目录  
  160.             ftpClient.changeWorkingDirectory("/data");  
  161.               
  162.             // 列出该目录下所有文件  
  163.             FTPFile[] files = ftpClient.listFiles();  
  164.               
  165.             // 遍历所有文件,找到指定的文件  
  166.             for (FTPFile file : files) {  
  167.                 if (file.getName().equals(FileName)) {  
  168.                     //根据绝对路径初始化文件  
  169.                     File localFile = new File(FilePath);  
  170.                       
  171.                     // 输出流  
  172.                     OutputStream outputStream = new FileOutputStream(localFile);  
  173.                       
  174.                     // 下载文件  
  175.                     ftpClient.retrieveFile(file.getName(), outputStream);  
  176.                       
  177.                     //关闭流  
  178.                     outputStream.close();  
  179.                 }  
  180.             }  
  181.               
  182.             //退出登陆FTP,关闭ftpCLient的连接  
  183.             ftpClient.logout();  
  184.             ftpClient.disconnect();  
  185.               
  186.               
  187.         } catch (IOException e) {  
  188.             // TODO Auto-generated catch block  
  189.             e.printStackTrace();  
  190.         }  
  191.           
  192.         return true;  
  193.     }  
  194.       
  195. }</span></strong> 

Java使用FTP上传文件被损坏的问题

原因

  首先,此问题是因为FTP协议定义的数据传输方式有关,当Java FTP客户端使用ASCII传输时会发现有些上传的文件已经被损坏。

 

FTP协议规定了两种传输方式分别是ASCII与binary方式:

  1. ASCII 方式,这种机制指,在针对传输内容是 ASCII 码文本时,文件内容会被调整,有时会造成传输的文件被损坏, ASCII 方式会把文件中的某些字符串位丢弃,所以不能保证文件数据的每一位都是重要的。
  2. 二进制方式,首先二进制方式保证了文件内容所有数据位都是重要的。
  3. 经过验证在传输文件类型为非文本内容的文件,使用 ASCII 传输方式造成 copy 的文件已经损坏。

示例代码(注意FTP.BINARY_FILE_TYPE/FTP.ASCII_FILE_TYPE):

 

  1. /** 
  2.  * 向远程服务器上传资源 
  3.  * @param destResource 上传文件对象 
  4.  * @return {true:成功;false:失败} 
  5.  * @throws IOException IOException 
  6.  */  
  7. public boolean uploadFile(File destResource) throws IOException {  
  8.     InputStream ins = (new FileInputStream(destResource));  
  9.     ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  
  10.     // ftpClient.setFileType(FTP.ASCII_FILE_TYPE);  
  11.     ftpClient.changeWorkingDirectory("tmp");  
  12.     boolean rtnFlag = ftpClient.storeFile(destResource.getName(), ins);  
  13.     ins.close();  
  14.     return rtnFlag;  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值