【转】Android 服务器之SFTP服务器上传下载功能
原文网址:http://blog.csdn.net/tanghua0809/article/details/47056327
本文主要是讲解Android服务器之SFTP服务器的上传下载功能,也是对之前所做项目的整理。
主要的代码块如下所示,对代码中相应地方稍作调整,复制粘贴到项目即可以使用,代码中会提供相应注释。
1.MainActivity
- public class MainActivity extends Activity implements OnClickListener{
- private final String TAG="MainActivity";
- private Button buttonUpLoad = null;
- private Button buttonDownLoad = null;
- private SFTPUtils sftp;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_sftpmain);
- init();
- }
- public void init(){
- //获取控件对象
- buttonUpLoad = (Button) findViewById(R.id.button_upload);
- buttonDownLoad = (Button) findViewById(R.id.button_download);
- //设置控件对应相应函数
- buttonUpLoad.setOnClickListener(this);
- buttonDownLoad.setOnClickListener(this);
- sftp = new SFTPUtils("SFTP服务器IP", "用户名","密码");
- }
- public void onClick(final View v) {
- // TODO Auto-generated method stub
- new Thread() {
- @Override
- public void run() {
- //这里写入子线程需要做的工作
- switch (v.getId()) {
- case R.id.button_upload: {
- //上传文件
- Log.d(TAG,"上传文件");
- String localPath = "sdcard/xml/";
- String remotePath = "test";
- sftp.connect();
- Log.d(TAG,"连接成功");
- sftp.uploadFile(remotePath,"APPInfo.xml", localPath, "APPInfo.xml");
- Log.d(TAG,"上传成功");
- sftp.disconnect();
- Log.d(TAG,"断开连接");
- }
- break;
- case R.id.button_download: {
- //下载文件
- Log.d(TAG,"下载文件");
- String localPath = "sdcard/download/";
- String remotePath = "test";
- sftp.connect();
- Log.d(TAG,"连接成功");
- sftp.downloadFile(remotePath, "APPInfo.xml", localPath, "APPInfo.xml");
- Log.d(TAG,"下载成功");
- sftp.disconnect();
- Log.d(TAG,"断开连接");
- }
- break;
- default:
- break;
- }
- }
- }.start();
- };
- }
2.SFTPUtils
- public class SFTPUtils {
- private String TAG="SFTPUtils";
- private String host;
- private String username;
- private String password;
- private int port = 22;
- private ChannelSftp sftp = null;
- private Session sshSession = null;
- public SFTPUtils (String host, String username, String password) {
- this.host = host;
- this.username = username;
- this.password = password;
- }
- /**
- * connect server via sftp
- */
- public ChannelSftp connect() {
- JSch jsch = new JSch();
- try {
- sshSession = jsch.getSession(username, host, port);
- sshSession.setPassword(password);
- Properties sshConfig = new Properties();
- sshConfig.put("StrictHostKeyChecking", "no");
- sshSession.setConfig(sshConfig);
- sshSession.connect();
- Channel channel = sshSession.openChannel("sftp");
- if (channel != null) {
- channel.connect();
- } else {
- Log.e(TAG, "channel connecting failed.");
- }
- sftp = (ChannelSftp) channel;
- } catch (JSchException e) {
- e.printStackTrace();
- }
- return sftp;
- }
- /**
- * 断开服务器
- */
- public void disconnect() {
- if (this.sftp != null) {
- if (this.sftp.isConnected()) {
- this.sftp.disconnect();
- Log.d(TAG,"sftp is closed already");
- }
- }
- if (this.sshSession != null) {
- if (this.sshSession.isConnected()) {
- this.sshSession.disconnect();
- Log.d(TAG,"sshSession is closed already");
- }
- }
- }
- /**
- * 单个文件上传
- * @param remotePath
- * @param remoteFileName
- * @param localPath
- * @param localFileName
- * @return
- */
- public boolean uploadFile(String remotePath, String remoteFileName,
- String localPath, String localFileName) {
- FileInputStream in = null;
- try {
- createDir(remotePath);
- System.out.println(remotePath);
- File file = new File(localPath + localFileName);
- in = new FileInputStream(file);
- System.out.println(in);
- sftp.put(in, remoteFileName);
- System.out.println(sftp);
- return true;
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (SftpException e) {
- e.printStackTrace();
- } finally {
- if (in != null) {
- try {
- in.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- return false;
- }
- /**
- * 批量上传
- * @param remotePath
- * @param localPath
- * @param del
- * @return
- */
- public boolean bacthUploadFile(String remotePath, String localPath,
- boolean del) {
- try {
- File file = new File(localPath);
- File[] files = file.listFiles();
- for (int i = 0; i < files.length; i++) {
- if (files[i].isFile()
- && files[i].getName().indexOf("bak") == -1) {
- synchronized(remotePath){
- if (this.uploadFile(remotePath, files[i].getName(),
- localPath, files[i].getName())
- && del) {
- deleteFile(localPath + files[i].getName());
- }
- }
- }
- }
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- this.disconnect();
- }
- return false;
- }
- /**
- * 批量下载文件
- *
- * @param remotPath
- * 远程下载目录(以路径符号结束)
- * @param localPath
- * 本地保存目录(以路径符号结束)
- * @param fileFormat
- * 下载文件格式(以特定字符开头,为空不做检验)
- * @param del
- * 下载后是否删除sftp文件
- * @return
- */
- @SuppressWarnings("rawtypes")
- public boolean batchDownLoadFile(String remotPath, String localPath,
- String fileFormat, boolean del) {
- try {
- connect();
- Vector v = listFiles(remotPath);
- if (v.size() > 0) {
- Iterator it = v.iterator();
- while (it.hasNext()) {
- LsEntry entry = (LsEntry) it.next();
- String filename = entry.getFilename();
- SftpATTRS attrs = entry.getAttrs();
- if (!attrs.isDir()) {
- if (fileFormat != null && !"".equals(fileFormat.trim())) {
- if (filename.startsWith(fileFormat)) {
- if (this.downloadFile(remotPath, filename,
- localPath, filename)
- && del) {
- deleteSFTP(remotPath, filename);
- }
- }
- } else {
- if (this.downloadFile(remotPath, filename,
- localPath, filename)
- && del) {
- deleteSFTP(remotPath, filename);
- }
- }
- }
- }
- }
- } catch (SftpException e) {
- e.printStackTrace();
- } finally {
- this.disconnect();
- }
- return false;
- }
- /**
- * 单个文件下载
- * @param remotePath
- * @param remoteFileName
- * @param localPath
- * @param localFileName
- * @return
- */
- public boolean downloadFile(String remotePath, String remoteFileName,
- String localPath, String localFileName) {
- try {
- sftp.cd(remotePath);
- File file = new File(localPath + localFileName);
- mkdirs(localPath + localFileName);
- sftp.get(remoteFileName, new FileOutputStream(file));
- return true;
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (SftpException e) {
- e.printStackTrace();
- }
- return false;
- }
- /**
- * 删除文件
- * @param filePath
- * @return
- */
- public boolean deleteFile(String filePath) {
- File file = new File(filePath);
- if (!file.exists()) {
- return false;
- }
- if (!file.isFile()) {
- return false;
- }
- return file.delete();
- }
- public boolean createDir(String createpath) {
- try {
- if (isDirExist(createpath)) {
- this.sftp.cd(createpath);
- Log.d(TAG,createpath);
- return true;
- }
- String pathArry[] = createpath.split("/");
- StringBuffer filePath = new StringBuffer("/");
- for (String path : pathArry) {
- if (path.equals("")) {
- continue;
- }
- filePath.append(path + "/");
- if (isDirExist(createpath)) {
- sftp.cd(createpath);
- } else {
- sftp.mkdir(createpath);
- sftp.cd(createpath);
- }
- }
- this.sftp.cd(createpath);
- return true;
- } catch (SftpException e) {
- e.printStackTrace();
- }
- return false;
- }
- /**
- * 判断目录是否存在
- * @param directory
- * @return
- */
- @SuppressLint("DefaultLocale")
- public boolean isDirExist(String directory) {
- boolean isDirExistFlag = false;
- try {
- SftpATTRS sftpATTRS = sftp.lstat(directory);
- isDirExistFlag = true;
- return sftpATTRS.isDir();
- } catch (Exception e) {
- if (e.getMessage().toLowerCase().equals("no such file")) {
- isDirExistFlag = false;
- }
- }
- return isDirExistFlag;
- }
- public void deleteSFTP(String directory, String deleteFile) {
- try {
- sftp.cd(directory);
- sftp.rm(deleteFile);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 创建目录
- * @param path
- */
- public void mkdirs(String path) {
- File f = new File(path);
- String fs = f.getParent();
- f = new File(fs);
- if (!f.exists()) {
- f.mkdirs();
- }
- }
- /**
- * 列出目录文件
- * @param directory
- * @return
- * @throws SftpException
- */
- @SuppressWarnings("rawtypes")
- public Vector listFiles(String directory) throws SftpException {
- return sftp.ls(directory);
- }
- }
3.导入jsch-0.1.52.jar,这个包网上有下载。注意一定要把它放到工程的libs目录下。
4.布局文件:activity_sftpmain.xml
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- >
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textStyle="bold"
- android:textSize="24dip"
- android:layout_gravity="center"
- android:text="SFTP上传下载测试 "/>
- <Button
- android:id="@+id/button_upload"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="上传"
- />
- <Button
- android:id="@+id/button_download"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="下载"
- />
- </LinearLayout>
5.Manifest文件配置
- <uses-permission android:name="android.permission.INTERNET" />
- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
【转】Android 服务器之SFTP服务器上传下载功能的更多相关文章
- 【转】Android 服务器之SFTP服务器上传下载功能 -- 不错
原文网址:http://blog.csdn.net/tanghua0809/article/details/47056327 本文主要是讲解Android服务器之SFTP服务器的上传下载功能,也是对之 ...
- java 通过sftp服务器上传下载删除文件
最近做了一个sftp服务器文件下载的功能,mark一下: 首先是一个SftpClientUtil 类,封装了对sftp服务器文件上传.下载.删除的方法 import java.io.File; imp ...
- Android连接socket服务器上传下载多个文件
android连接socket服务器上传下载多个文件1.socket服务端SocketServer.java public class SocketServer { ;// 端口号,必须与客户端一致 ...
- 向linux服务器上传下载文件方式收集
向linux服务器上传下载文件方式收集 1. scp [优点]简单方便,安全可靠:支持限速参数[缺点]不支持排除目录[用法] scp就是secure copy,是用来进行远程文件拷贝的.数据传输使用 ...
- Linux下不借助工具实现远程linux服务器上传下载文件
# Linux下不借助工具实现远程linux服务器上传下载文件 ## 简介 - Linux下自带ssh工具,可以实现远程Linux服务器的功能- Linux下自带scp工具,可以实现文件传输功能 ## ...
- JavaWeb实现文件上传下载功能实例解析
转:http://www.cnblogs.com/xdp-gacl/p/4200090.html JavaWeb实现文件上传下载功能实例解析 在Web应用系统开发中,文件上传和下载功能是非常常用的功能 ...
- JavaWeb实现文件上传下载功能实例解析 (好用)
转: JavaWeb实现文件上传下载功能实例解析 转:http://www.cnblogs.com/xdp-gacl/p/4200090.html JavaWeb实现文件上传下载功能实例解析 在Web ...
- SFTP远程连接服务器上传下载文件-qt4.8.0-vs2010编译器-项目实例
本项目仅测试远程连接服务器,支持上传,下载文件,更多功能开发请看API自行开发. 环境:win7系统,Qt4.8.0版本,vs2010编译器 qt4.8.0-vs2010编译器项目实例下载地址:CSD ...
- 我的代码库-Java8实现FTP与SFTP文件上传下载
有网上的代码,也有自己的理解,代码备份 一般连接windows服务器使用FTP,连接linux服务器使用SFTP.linux都是通过SFTP上传文件,不需要额外安装,非要使用FTP的话,还得安装FTP ...
随机推荐
- mysql之触发器
触发器 MySQL语句在需要时被执行,存储过程也是如此.但是,如果你想要某条语句(或某些语句)在事件发生时自动执行,怎么办呢?例如:每当增加一个顾客到某个数据库表时,都检查其电话号码格式是否正 ...
- mysql之select(一)
select 初始准备工作: 1.建木瓜库并选中 create database mugua; use mugua; 2.创建商品表.栏目表.品牌表 create table goods ( good ...
- 使用secureCRT远程Linux,出现远程主机拒绝连接
1.查看是否开启远程连接, 控制面板->程序和功能->打开或关闭windows功能->勾选telnet服务器和telnet客户端2.cmd命令行输入telnet ip地址 端口号(比 ...
- MyEclipse — Maven+Spring+Struts+Hibernate 整合 [学习笔记-3]
引入Struts2 在pom.xml中加入jar包 <!-- struts2 --> <dependency> <groupId>org.apache.struts ...
- web.xml中servlet初始化参数的设置
<context-param><param-name>param1</param-name><param-value>value1</param- ...
- JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-001Mapping basic properties(@Basic、@Access、access="noop"、@Formula、@ColumnTransformer、@Generated、 @ColumnDefaul、@Temporal、@Enumerated)
一.简介 在JPA中,默认所有属性都会persist,属性要属于以下3种情况,Hibernate在启动时会报错 1.java基本类型或包装类 2.有注解 @Embedded 3.有实现java.io. ...
- QWidget的六个刷新函数(居然有QWidget::erase函数,且并不产生绘制事件)
Qt paintevent事件 一.主要理解一下几个方法和属性: 1.QWidget * QScrollView::viewport () const 2.void QWidget::paintE ...
- hdu - 1829 A Bug's Life (并查集)&&poj - 2492 A Bug's Life && poj 1703 Find them, Catch them
http://acm.hdu.edu.cn/showproblem.php?pid=1829 http://poj.org/problem?id=2492 臭虫有两种性别,并且只有异性相吸,给定n条臭 ...
- MTK平台缩写
HSPA:High Speed Packet Access smartphone application processor,高速分组接入的智能手机应用程序处理器 META mode:Mobile E ...
- Oracle数据库之二
SELECT查询 函数分为: 单行函数 -- 一条记录进入,一条记录输出 多行函数(分组函数)-- 多条记录进入,按组输出 单行函数: select id,first_name,nvl(commiss ...