您的位置:首页 > 移动开发 > Android开发

【转】Android 服务器之SFTP服务器上传下载功能

2016-07-17 14:25 399 查看
原文网址:http://blog.csdn.net/tanghua0809/article/details/47056327

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

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

1.MainActivity

[java] view plain copy

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

[java] view plain copy

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

[html] view plain copy

<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文件配置

[java] view plain copy

<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"/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: