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

本文主要是讲解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"/>






  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
要在Android应用程序中从SFTP服务器下载文件,您可以使用JSch库来实现。以下是一个简单的示例代码片段,演示了如何进行SFTP文件下载: ```java import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; public class SftpDownloader { private static final String HOST = "your_sftp_host"; private static final int PORT = 22; private static final String USERNAME = "your_sftp_username"; private static final String PASSWORD = "your_sftp_password"; private static final String REMOTE_FILE_PATH = "/path/to/remote/file"; private static final String LOCAL_FILE_PATH = "/path/to/local/file"; public static void downloadFile() { JSch ssh = new JSch(); Session session = null; try { session = ssh.getSession(USERNAME, HOST, PORT); session.setPassword(PASSWORD); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftpChannel = (ChannelSftp) channel; InputStream inputStream = sftpChannel.get(REMOTE_FILE_PATH); OutputStream outputStream = new FileOutputStream(LOCAL_FILE_PATH); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } inputStream.close(); outputStream.close(); sftpChannel.disconnect(); channel.disconnect(); session.disconnect(); System.out.println("File downloaded successfully."); } catch (Exception e) { e.printStackTrace(); } } } ``` 请确保将`your_sftp_host`,`your_sftp_username`,`your_sftp_password`,`/path/to/remote/file`和`/path/to/local/file`替换为实际的SFTP服务器主机,用户名,密码以及远程和本地文件的路径。 以上代码将从SFTP服务器下载文件并保存在本地位置。您可以根据您的需求进行调整和修改。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值