【转】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"/>
补充:
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();
}
【转】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 ...
随机推荐
- java 正则表达式(一)
1匹配验证-验证Email是否正确 Java | 复制 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public static void main(String[] args) ...
- scikit-learn系列之如何存储和导入机器学习模型
scikit-learn系列之如何存储和导入机器学习模型 如何存储和导入机器学习模型 找到一个准确的机器学习模型,你的项目并没有完成.本文中你将学习如何使用scikit-learn来存储和导入机器 ...
- 40.DOM读取XML
main.cpp #include <QtGui> #include <iostream> #include "domparser.h" int main( ...
- 29.QT主窗口加widget
运行效果 widget布局showwidget.h #ifndef SHOWWIDGET_H #define SHOWWIDGET_H #include <QWidget> #includ ...
- Android设计模式——抽象工厂方法模式
1.抽象工厂方法模式:为了创建一组或相互依赖的对象提供一个接口,而不需要指定它们是具体类……无语 2.找个代码看看: 抽象工厂类<成员为接口> /** * 抽象工厂 * */ public ...
- JSON是什么?为JavaScript准备的数据格式
JSON是什么?为JavaScript准备的数据格式 还不了解JSON是什么?看了下面这篇文章,您对JSON是什么应该能够有了一个比较清晰的概念. JSON 即 JavaScript. Object ...
- 像素点的Hessian矩阵
最近开始学习图像处理相关知识,碰到对像素点求黑塞矩阵查了资料才搞懂. 给定一个图像f(x,y)上的一点(x,y).其黑塞矩阵如下: 因为导数的公式是f'(x)=(f(x+dx)-f(x))/dx在数字 ...
- ZBrush中遮罩的概念及使用
刚接触设计软件的小伙伴有可能不知道什么叫做遮罩,遮罩的概念是什么,顾名思义,遮罩就是可以将局部进行遮挡,使用它可以锁定和保护我们不想改变的模型位置,即被遮罩的部分将不参与任何编辑. ZBrush®软件 ...
- Day 02 - 02 编程语言的分类
编程语言的分类 机器语言分为: 1.机器语言 优点:执行代码效率非常快 缺点:开发效率低 2.汇编语言 优点(相对于机器语言):开发效率高 缺点(相对于机器语言):执行效率低 3.高级语言 解释型(同 ...
- nodejs+express搭建服务器
1.Express 是一个简洁而灵活的 node.js Web应用框架, 提供了一系列强大特性帮助你创建各种 Web 应用,和丰富的 HTTP 工具. 使用 Express 可以快速地搭建一个完整功能 ...