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

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

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

1.MainActivity

  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. public void init(){
  13. //获取控件对象
  14. buttonUpLoad = (Button) findViewById(R.id.button_upload);
  15. buttonDownLoad = (Button) findViewById(R.id.button_download);
  16. //设置控件对应相应函数
  17. buttonUpLoad.setOnClickListener(this);
  18. buttonDownLoad.setOnClickListener(this);
  19. sftp = new SFTPUtils("SFTP服务器IP", "用户名","密码");
  20. }
  21. public void onClick(final View v) {
  22. // TODO Auto-generated method stub
  23. new Thread() {
  24. @Override
  25. public void run() {
  26. //这里写入子线程需要做的工作
  27. switch (v.getId()) {
  28. case R.id.button_upload: {
  29. //上传文件
  30. Log.d(TAG,"上传文件");
  31. String localPath = "sdcard/xml/";
  32. String remotePath = "test";
  33. sftp.connect();
  34. Log.d(TAG,"连接成功");
  35. sftp.uploadFile(remotePath,"APPInfo.xml", localPath, "APPInfo.xml");
  36. Log.d(TAG,"上传成功");
  37. sftp.disconnect();
  38. Log.d(TAG,"断开连接");
  39. }
  40. break;
  41. case R.id.button_download: {
  42. //下载文件
  43. Log.d(TAG,"下载文件");
  44. String localPath = "sdcard/download/";
  45. String remotePath = "test";
  46. sftp.connect();
  47. Log.d(TAG,"连接成功");
  48. sftp.downloadFile(remotePath, "APPInfo.xml", localPath, "APPInfo.xml");
  49. Log.d(TAG,"下载成功");
  50. sftp.disconnect();
  51. Log.d(TAG,"断开连接");
  52. }
  53. break;
  54. default:
  55. break;
  56. }
  57. }
  58. }.start();
  59. };
  60. }

2.SFTPUtils

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

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. <Button
  21. android:id="@+id/button_download"
  22. android:layout_width="fill_parent"
  23. android:layout_height="wrap_content"
  24. android:text="下载"
  25. />
  26. </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"/>

【转】Android 服务器之SFTP服务器上传下载功能的更多相关文章

  1. 【转】Android 服务器之SFTP服务器上传下载功能 -- 不错

    原文网址:http://blog.csdn.net/tanghua0809/article/details/47056327 本文主要是讲解Android服务器之SFTP服务器的上传下载功能,也是对之 ...

  2. java 通过sftp服务器上传下载删除文件

    最近做了一个sftp服务器文件下载的功能,mark一下: 首先是一个SftpClientUtil 类,封装了对sftp服务器文件上传.下载.删除的方法 import java.io.File; imp ...

  3. Android连接socket服务器上传下载多个文件

    android连接socket服务器上传下载多个文件1.socket服务端SocketServer.java public class SocketServer { ;// 端口号,必须与客户端一致 ...

  4. 向linux服务器上传下载文件方式收集

    向linux服务器上传下载文件方式收集 1. scp [优点]简单方便,安全可靠:支持限速参数[缺点]不支持排除目录[用法] scp就是secure copy,是用来进行远程文件拷贝的.数据传输使用 ...

  5. Linux下不借助工具实现远程linux服务器上传下载文件

    # Linux下不借助工具实现远程linux服务器上传下载文件 ## 简介 - Linux下自带ssh工具,可以实现远程Linux服务器的功能- Linux下自带scp工具,可以实现文件传输功能 ## ...

  6. JavaWeb实现文件上传下载功能实例解析

    转:http://www.cnblogs.com/xdp-gacl/p/4200090.html JavaWeb实现文件上传下载功能实例解析 在Web应用系统开发中,文件上传和下载功能是非常常用的功能 ...

  7. JavaWeb实现文件上传下载功能实例解析 (好用)

    转: JavaWeb实现文件上传下载功能实例解析 转:http://www.cnblogs.com/xdp-gacl/p/4200090.html JavaWeb实现文件上传下载功能实例解析 在Web ...

  8. SFTP远程连接服务器上传下载文件-qt4.8.0-vs2010编译器-项目实例

    本项目仅测试远程连接服务器,支持上传,下载文件,更多功能开发请看API自行开发. 环境:win7系统,Qt4.8.0版本,vs2010编译器 qt4.8.0-vs2010编译器项目实例下载地址:CSD ...

  9. 我的代码库-Java8实现FTP与SFTP文件上传下载

    有网上的代码,也有自己的理解,代码备份 一般连接windows服务器使用FTP,连接linux服务器使用SFTP.linux都是通过SFTP上传文件,不需要额外安装,非要使用FTP的话,还得安装FTP ...

随机推荐

  1. 使用Ninject来解决程序中组件的耦合问题

    1.为什么要用Ninject? Ninject是一个IOC容器用来解决程序中组件的耦合问题,它的目的在于做到最少配置.其他的的IOC工具过于依赖配置文件,需要使用assembly-qualified名 ...

  2. Good Bye 2015 C. New Year and Domino 二维前缀

    C. New Year and Domino   They say "years are like dominoes, tumbling one after the other". ...

  3. linux下tigervnc-servere服务的安装与使用

    关于tigervnc-servere的安装,可以直接使用本地yum源进行安装. [root@ ~]# yum install tigervnc-server -y 其中tigervnc的主要配置文件位 ...

  4. PushBackInputStream与PushBackInputStreamReader的用法

    举个例子:获取XX内容 PushBackInputStream pb=new PushBackInputStream(in,4);//4制定缓冲区大小 byte[] buf=new byte[4]; ...

  5. iOS开发多线程--技术方案

    pthread 实现多线程操作 代码实现: void * run(void *param) {    for (NSInteger i = 0; i < 1000; i++) {         ...

  6. ios开发 ad hoc

    iOS证书分2种,1种是开发证书,用来给你(开发人员)做真机测试的:1种是发布证书,发布证书又分发布到app store的(这里不提及)和发布测试的ad hoc证书. 那ad hoc证书和开发证书区别 ...

  7. SPRING IN ACTION 第4版笔记-第十一章Persisting data with object-relational mapping-005Spring-Data-JPA例子的代码

    一.结构 二.Repository层 1. package spittr.db; import java.util.List; import org.springframework.data.jpa. ...

  8. J-link V8固件升级记

    http://blog.sina.com.cn/s/blog_5bdee3020101khfy.html 好久没为电子工程事业尽份力了!今天也稍微努把力!写写我是如何升级J-link的固件的吧! J- ...

  9. Seajs demo

    index.html <!doctype html> <html lang="en"> <head> <meta charset=&quo ...

  10. angularjs tips

    angular-ui #1 .Impossible to disable fade in modal angularjs ui modal 去掉fade in效果: googleA googleB # ...