fstp下载转载的文章,这个很好用,只需要修改你的路径还有文件名就可以了

本文介绍如何在Android应用中实现SFTP服务器的文件上传和下载功能,提供了完整的代码示例,包括创建目录、单个及批量文件的上传与下载等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

                                            
                

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

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

1.MainActivity

  1. public class MainActivity extends Activity implements OnClickListener{
  2.     private final  String TAG=“MainActivity”;
  3.     private Button buttonUpLoad = ;  
  4.     private Button buttonDownLoad = ;  
  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. }


2.SFTPUtils

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


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

4.布局文件:activity_sftpmain.xml

  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.    <Button
  15.         android:id="@+id/button_upload"
  16.         android:layout_width="fill_parent"
  17.         android:layout_height="wrap_content"
  18.         android:text="上传"
  19.         />
  20.    
  21.    <Button
  22.         android:id="@+id/button_download"
  23.         android:layout_width="fill_parent"
  24.         android:layout_height="wrap_content"
  25.         android:text="下载"
  26.         />
  27. </LinearLayout>


5.Manifest文件配置

  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"/>






           

               

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值