zoukankan      html  css  js  c++  java
  • 【转】Android 服务器之SFTP服务器上传下载功能 -- 不错

    原文网址:http://blog.csdn.net/tanghua0809/article/details/47056327

    本文主要是讲解Android服务器之SFTP服务器的上传下载功能,也是对之前所做项目的整理。

    主要的代码块如下所示,对代码中相应地方稍作调整,复制粘贴到项目即可以使用,代码中会提供相应注释。

    1.MainActivity

    [java] view plain copy
     
    1. public class MainActivity extends Activity implements OnClickListener{  
    2.     private final  String TAG="MainActivity";  
    3.     private Button buttonUpLoad = null;    
    4.     private Button buttonDownLoad = null;    
    5.     private SFTPUtils sftp;  
    6.     @Override  
    7.     protected void onCreate(Bundle savedInstanceState) {  
    8.         super.onCreate(savedInstanceState);  
    9.         setContentView(R.layout.activity_sftpmain);  
    10.         init();  
    11.     }  
    12.           
    13.     public void init(){  
    14.           //获取控件对象   
    15.         buttonUpLoad = (Button) findViewById(R.id.button_upload);    
    16.         buttonDownLoad = (Button) findViewById(R.id.button_download);    
    17.         //设置控件对应相应函数    
    18.         buttonUpLoad.setOnClickListener(this);    
    19.         buttonDownLoad.setOnClickListener(this);  
    20.         sftp = new SFTPUtils("SFTP服务器IP", "用户名","密码");  
    21.     }  
    22.        public void onClick(final View v) {    
    23.             // TODO Auto-generated method stub    
    24.            new Thread() {  
    25.                @Override  
    26.                public void run() {  
    27.                     //这里写入子线程需要做的工作  
    28.                       
    29.             switch (v.getId()) {    
    30.                     case R.id.button_upload: {    
    31.                     //上传文件   
    32.                     Log.d(TAG,"上传文件");     
    33.                     String localPath = "sdcard/xml/";  
    34.                     String remotePath = "test";  
    35.                     sftp.connect();   
    36.                     Log.d(TAG,"连接成功");   
    37.                     sftp.uploadFile(remotePath,"APPInfo.xml", localPath, "APPInfo.xml");  
    38.                     Log.d(TAG,"上传成功");   
    39.                     sftp.disconnect();  
    40.                     Log.d(TAG,"断开连接");   
    41.                   }    
    42.                         break;   
    43.                               
    44.                     case R.id.button_download: {    
    45.                             //下载文件  
    46.                            Log.d(TAG,"下载文件");   
    47.                            String localPath = "sdcard/download/";  
    48.                            String remotePath = "test";  
    49.                            sftp.connect();   
    50.                            Log.d(TAG,"连接成功");   
    51.                            sftp.downloadFile(remotePath, "APPInfo.xml", localPath, "APPInfo.xml");  
    52.                            Log.d(TAG,"下载成功");   
    53.                            sftp.disconnect();  
    54.                            Log.d(TAG,"断开连接");   
    55.                             
    56.                           }    
    57.                           break;    
    58.                      default:    
    59.                           break;    
    60.             }        
    61.         }   
    62.            }.start();  
    63.           };  
    64. }  
    65.       

    2.SFTPUtils

    [java] view plain copy
     
    1. public class SFTPUtils {  
    2.       
    3.     private String TAG="SFTPUtils";  
    4.     private String host;  
    5.     private String username;  
    6.     private String password;  
    7.     private int port = 22;  
    8.     private ChannelSftp sftp = null;  
    9.     private Session sshSession = null;  
    10.   
    11.     public SFTPUtils (String host, String username, String password) {  
    12.         this.host = host;  
    13.         this.username = username;  
    14.         this.password = password;  
    15.     }  
    16.           
    17.     /** 
    18.      * connect server via sftp 
    19.      */  
    20.     public ChannelSftp connect() {  
    21.         JSch jsch = new JSch();  
    22.         try {  
    23.             sshSession = jsch.getSession(username, host, port);  
    24.             sshSession.setPassword(password);  
    25.             Properties sshConfig = new Properties();  
    26.             sshConfig.put("StrictHostKeyChecking", "no");  
    27.             sshSession.setConfig(sshConfig);  
    28.             sshSession.connect();  
    29.             Channel channel = sshSession.openChannel("sftp");  
    30.             if (channel != null) {  
    31.                 channel.connect();  
    32.             } else {  
    33.                 Log.e(TAG, "channel connecting failed.");  
    34.             }  
    35.             sftp = (ChannelSftp) channel;  
    36.         } catch (JSchException e) {  
    37.             e.printStackTrace();  
    38.         }  
    39.         return sftp;  
    40.     }  
    41.       
    42.               
    43. /** 
    44.  * 断开服务器 
    45.  */  
    46.     public void disconnect() {  
    47.         if (this.sftp != null) {  
    48.             if (this.sftp.isConnected()) {  
    49.                 this.sftp.disconnect();  
    50.                 Log.d(TAG,"sftp is closed already");  
    51.             }  
    52.         }  
    53.         if (this.sshSession != null) {  
    54.             if (this.sshSession.isConnected()) {  
    55.                 this.sshSession.disconnect();  
    56.                 Log.d(TAG,"sshSession is closed already");  
    57.             }  
    58.         }  
    59.     }  
    60.   
    61.     /** 
    62.      * 单个文件上传 
    63.      * @param remotePath 
    64.      * @param remoteFileName 
    65.      * @param localPath 
    66.      * @param localFileName 
    67.      * @return 
    68.      */  
    69.     public boolean uploadFile(String remotePath, String remoteFileName,  
    70.             String localPath, String localFileName) {  
    71.         FileInputStream in = null;  
    72.         try {  
    73.             createDir(remotePath);  
    74.             System.out.println(remotePath);  
    75.             File file = new File(localPath + localFileName);  
    76.             in = new FileInputStream(file);  
    77.             System.out.println(in);  
    78.             sftp.put(in, remoteFileName);  
    79.             System.out.println(sftp);  
    80.             return true;  
    81.         } catch (FileNotFoundException e) {  
    82.             e.printStackTrace();  
    83.         } catch (SftpException e) {  
    84.             e.printStackTrace();  
    85.         } finally {  
    86.             if (in != null) {  
    87.                 try {  
    88.                     in.close();  
    89.                 } catch (IOException e) {  
    90.                     e.printStackTrace();  
    91.                 }  
    92.             }  
    93.         }  
    94.         return false;  
    95.     }  
    96.       
    97.     /** 
    98.      * 批量上传 
    99.      * @param remotePath 
    100.      * @param localPath 
    101.      * @param del 
    102.      * @return 
    103.      */  
    104.     public boolean bacthUploadFile(String remotePath, String localPath,  
    105.             boolean del) {  
    106.         try {  
    107.             File file = new File(localPath);  
    108.             File[] files = file.listFiles();  
    109.             for (int i = 0; i < files.length; i++) {  
    110.                 if (files[i].isFile()  
    111.                         && files[i].getName().indexOf("bak") == -1) {  
    112.                     synchronized(remotePath){  
    113.                         if (this.uploadFile(remotePath, files[i].getName(),  
    114.                             localPath, files[i].getName())  
    115.                             && del) {  
    116.                         deleteFile(localPath + files[i].getName());  
    117.                         }  
    118.                     }  
    119.                 }  
    120.             }  
    121.             return true;  
    122.         } catch (Exception e) {  
    123.             e.printStackTrace();  
    124.         } finally {  
    125.             this.disconnect();  
    126.         }  
    127.         return false;  
    128.   
    129.     }  
    130.       
    131.     /** 
    132.      * 批量下载文件 
    133.      *  
    134.      * @param remotPath 
    135.      *            远程下载目录(以路径符号结束) 
    136.      * @param localPath 
    137.      *            本地保存目录(以路径符号结束) 
    138.      * @param fileFormat 
    139.      *            下载文件格式(以特定字符开头,为空不做检验) 
    140.      * @param del 
    141.      *            下载后是否删除sftp文件 
    142.      * @return 
    143.      */  
    144.     @SuppressWarnings("rawtypes")  
    145.     public boolean batchDownLoadFile(String remotPath, String localPath,  
    146.             String fileFormat, boolean del) {  
    147.         try {  
    148.             connect();  
    149.             Vector v = listFiles(remotPath);  
    150.             if (v.size() > 0) {  
    151.   
    152.                 Iterator it = v.iterator();  
    153.                 while (it.hasNext()) {  
    154.                     LsEntry entry = (LsEntry) it.next();  
    155.                     String filename = entry.getFilename();  
    156.                     SftpATTRS attrs = entry.getAttrs();  
    157.                     if (!attrs.isDir()) {  
    158.                         if (fileFormat != null && !"".equals(fileFormat.trim())) {  
    159.                             if (filename.startsWith(fileFormat)) {  
    160.                                 if (this.downloadFile(remotPath, filename,  
    161.                                         localPath, filename)  
    162.                                         && del) {  
    163.                                     deleteSFTP(remotPath, filename);  
    164.                                 }  
    165.                             }  
    166.                         } else {  
    167.                             if (this.downloadFile(remotPath, filename,  
    168.                                     localPath, filename)  
    169.                                     && del) {  
    170.                                 deleteSFTP(remotPath, filename);  
    171.                             }  
    172.                         }  
    173.                     }  
    174.                 }  
    175.             }  
    176.         } catch (SftpException e) {  
    177.             e.printStackTrace();  
    178.         } finally {  
    179.             this.disconnect();  
    180.         }  
    181.         return false;  
    182.     }  
    183.   
    184.     /** 
    185.      * 单个文件下载 
    186.      * @param remotePath 
    187.      * @param remoteFileName 
    188.      * @param localPath 
    189.      * @param localFileName 
    190.      * @return 
    191.      */  
    192.     public boolean downloadFile(String remotePath, String remoteFileName,  
    193.             String localPath, String localFileName) {  
    194.         try {  
    195.             sftp.cd(remotePath);  
    196.             File file = new File(localPath + localFileName);  
    197.             mkdirs(localPath + localFileName);  
    198.             sftp.get(remoteFileName, new FileOutputStream(file));  
    199.             return true;  
    200.         } catch (FileNotFoundException e) {  
    201.             e.printStackTrace();  
    202.         } catch (SftpException e) {  
    203.             e.printStackTrace();  
    204.         }  
    205.   
    206.         return false;  
    207.     }  
    208.   
    209.     /** 
    210.      * 删除文件 
    211.      * @param filePath 
    212.      * @return 
    213.      */  
    214.     public boolean deleteFile(String filePath) {  
    215.         File file = new File(filePath);  
    216.             if (!file.exists()) {  
    217.                 return false;  
    218.             }  
    219.             if (!file.isFile()) {  
    220.                 return false;  
    221.             }  
    222.             return file.delete();  
    223.         }  
    224.           
    225.     public boolean createDir(String createpath) {  
    226.         try {  
    227.             if (isDirExist(createpath)) {  
    228.                 this.sftp.cd(createpath);  
    229.                 Log.d(TAG,createpath);  
    230.                 return true;  
    231.             }  
    232.             String pathArry[] = createpath.split("/");  
    233.             StringBuffer filePath = new StringBuffer("/");  
    234.             for (String path : pathArry) {  
    235.                 if (path.equals("")) {  
    236.                     continue;  
    237.                 }  
    238.                 filePath.append(path + "/");  
    239.                     if (isDirExist(createpath)) {  
    240.                         sftp.cd(createpath);  
    241.                     } else {  
    242.                         sftp.mkdir(createpath);  
    243.                         sftp.cd(createpath);  
    244.                     }  
    245.                 }  
    246.                 this.sftp.cd(createpath);  
    247.                   return true;  
    248.             } catch (SftpException e) {  
    249.                 e.printStackTrace();  
    250.             }  
    251.             return false;  
    252.         }  
    253.   
    254.     /** 
    255.      * 判断目录是否存在 
    256.      * @param directory 
    257.      * @return 
    258.      */  
    259.     @SuppressLint("DefaultLocale")   
    260.     public boolean isDirExist(String directory) {  
    261.         boolean isDirExistFlag = false;  
    262.         try {  
    263.             SftpATTRS sftpATTRS = sftp.lstat(directory);  
    264.             isDirExistFlag = true;  
    265.             return sftpATTRS.isDir();  
    266.         } catch (Exception e) {  
    267.             if (e.getMessage().toLowerCase().equals("no such file")) {  
    268.                 isDirExistFlag = false;  
    269.             }  
    270.         }  
    271.         return isDirExistFlag;  
    272.         }  
    273.       
    274.     public void deleteSFTP(String directory, String deleteFile) {  
    275.         try {  
    276.             sftp.cd(directory);  
    277.             sftp.rm(deleteFile);  
    278.         } catch (Exception e) {  
    279.             e.printStackTrace();  
    280.         }  
    281.     }  
    282.   
    283.     /** 
    284.      * 创建目录 
    285.      * @param path 
    286.      */  
    287.     public void mkdirs(String path) {  
    288.         File f = new File(path);  
    289.         String fs = f.getParent();  
    290.         f = new File(fs);  
    291.         if (!f.exists()) {  
    292.             f.mkdirs();  
    293.         }  
    294.     }  
    295.   
    296.     /** 
    297.      * 列出目录文件 
    298.      * @param directory 
    299.      * @return 
    300.      * @throws SftpException 
    301.      */  
    302.       
    303.     @SuppressWarnings("rawtypes")  
    304.     public Vector listFiles(String directory) throws SftpException {  
    305.         return sftp.ls(directory);  
    306.     }  
    307.       
    308. }  

    3.导入jsch-0.1.52.jar,这个包网上有下载。注意一定要把它放到工程的libs目录下。

    4.布局文件:activity_sftpmain.xml

    [html] view plain copy
     
    1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    2.     xmlns:tools="http://schemas.android.com/tools"  
    3.     android:layout_width="match_parent"  
    4.     android:layout_height="match_parent"  
    5.     android:orientation="vertical"  
    6.    >  
    7.  <TextView  
    8.         android:layout_width="wrap_content"  
    9.         android:layout_height="wrap_content"  
    10.         android:textStyle="bold"  
    11.         android:textSize="24dip"  
    12.         android:layout_gravity="center"  
    13.         android:text="SFTP上传下载测试 "/>  
    14.    
    15.     <Button  
    16.         android:id="@+id/button_upload"  
    17.         android:layout_width="fill_parent"  
    18.         android:layout_height="wrap_content"  
    19.         android:text="上传"  
    20.         />  
    21.       
    22.     <Button  
    23.         android:id="@+id/button_download"  
    24.         android:layout_width="fill_parent"  
    25.         android:layout_height="wrap_content"  
    26.         android:text="下载"  
    27.         />  
    28.   
    29. </LinearLayout>  



    5.Manifest文件配置

    [java] view plain copy
     
      1.    <uses-permission android:name="android.permission.INTERNET" />  
      2.    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
      3. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  

    补充:

    Jsch Suppressed: java.lang.ClassNotFoundException: Lorg.ietf.jgss.Oid

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(userName, remoteHost, port);
        session.setPassword(userPassword);
    
        Properties prop = new Properties();
        prop.put("StrictHostKeyChecking", "no");
        session.setConfig(prop);
    
        session.setConfig("PreferredAuthentications",
                    "password"); //add this line to your code
    
        session.connect();
    
        channel = session.openChannel("sftp");          
        channel.connect();
        channelSftp = (ChannelSftp)channel;
    
    } catch (Exception ex) {
        ex.printStackTrace();
        session.disconnect();
    }
  • 相关阅读:
    个人作业——软件工程实践总结&个人技术博客
    个人作业——软件评测
    结对第二次作业——某次疫情统计可视化的实现
    结对第一次—疫情统计可视化(原型设计)
    软工实践寒假作业(2/2)
    软工实践寒假作业(1/2)
    C#MD5判断文件是否修改
    Socket抓包工具WireShark使用
    C#窗体最大化最小化等比例缩放
    QMessageBox
  • 原文地址:https://www.cnblogs.com/wi100sh/p/5678503.html
Copyright © 2011-2022 走看看