文件系统之-JAVA Sftp远程操作:
转载:http://blog.csdn.net/lee272616/article/details/52789018
java远程操作文件服务器(linux),使用sftp协议
版本会持续更新,
当前版本:0.31
版本更新时间:2016-10-13
版本修正说明:
1.修正连接关闭,将关闭的方法改成私有,不允许使用者自行关闭(否则会导致连接池获取错误)
2.优化删除文件及文件夹,先判断文件或文件夹是否存在,然后再删除
前言:
sftp是Secure File Transfer Protocol的缩写,安全文件传送协议。可以为传输文件提供一种安全的加密方法。sftp 与 ftp 有着几乎一样的语法和功能。SFTP 为 SSH的一部分,是一种传输档案至 Blogger 伺服器的安全方式。其实在SSH软件包中,已经包含了一个叫作SFTP(Secure File Transfer Protocol)的安全文件传输子系统,SFTP本身没有单独的守护进程,它必须使用sshd守护进程(端口号默认是22)来完成相应的连接操作,所以从某种意义上来说,SFTP并不像一个服务器程序,而更像是一个客户端程序。SFTP同样是使用加密传输认证信息和传输的数据,所以,使用SFTP是非常安全的。但是,由于这种传输方式使用了加密/解密技术,所以传输效率比普通的FTP要低得多,如果您对网络安全性要求更高时,可以使用SFTP代替FTP。
本工具基于对JSch - Java Secure Channel进行的封装,linux服务器不用安装任何插件和软件
使用指南:
首先是jar包
- <dependency>
- <groupId>com.jcraft</groupId>
- <artifactId>jsch</artifactId>
- <version>0.1.42</version>
- </dependency>
Sftp协议工具类-v0.1
- package com.noryar.filesystem.utils;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Properties;
- import java.util.Vector;
- import org.apache.commons.lang.StringUtils;
- import com.jcraft.jsch.Channel;
- import com.jcraft.jsch.ChannelSftp;
- import com.jcraft.jsch.JSch;
- import com.jcraft.jsch.JSchException;
- import com.jcraft.jsch.Session;
- import com.jcraft.jsch.SftpException;
- /**
- * 文件工具类.
- * @author Leon Lee
- */
- public class SftpUtil {
- /**
- * 文件路径前缀. /ddit-remote
- */
- private static final String PRE_FIX = "/test-noryar";
- /**
- * 获取sftp协议连接.
- * @param host 主机名
- * @param port 端口
- * @param username 用户名
- * @param password 密码
- * @return 连接对象
- * @throws JSchException 异常
- */
- public static ChannelSftp getSftpConnect(final String host, final int port, final String username,
- final String password) throws JSchException {
- ChannelSftp sftp = null;
- JSch jsch = new JSch();
- jsch.getSession(username, host, port);
- Session 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");
- channel.connect();
- sftp = (ChannelSftp) channel;
- return sftp;
- }
- /**
- * 下载文件-sftp协议.
- * @param downloadFile 下载的文件
- * @param saveFile 存在本地的路径
- * @param sftp sftp连接
- * @return 文件
- * @throws Exception 异常
- */
- public static File download(final String downloadFile, final String saveFile, final ChannelSftp sftp)
- throws Exception {
- FileOutputStream os = null;
- File file = new File(saveFile);
- try {
- if (!file.exists()) {
- File parentFile = file.getParentFile();
- if (!parentFile.exists()) {
- parentFile.mkdirs();
- }
- file.createNewFile();
- }
- os = new FileOutputStream(file);
- List<String> list = formatPath(downloadFile);
- sftp.get(list.get(0) + list.get(1), os);
- } catch (Exception e) {
- exit(sftp);
- throw e;
- } finally {
- os.close();
- }
- return file;
- }
- /**
- * 下载文件-sftp协议.
- * @param downloadFile 下载的文件
- * @param saveFile 存在本地的路径
- * @param sftp sftp连接
- * @return 文件 byte[]
- * @throws Exception 异常
- */
- public static byte[] downloadAsByte(final String downloadFile, final ChannelSftp sftp) throws Exception {
- ByteArrayOutputStream os = new ByteArrayOutputStream();
- try {
- List<String> list = formatPath(downloadFile);
- sftp.get(list.get(0) + list.get(1), os);
- } catch (Exception e) {
- exit(sftp);
- throw e;
- } finally {
- os.close();
- }
- return os.toByteArray();
- }
- /**
- * 删除文件-sftp协议.
- * @param deleteFile 要删除的文件
- * @param sftp sftp连接
- * @throws Exception 异常
- */
- public static void rmFile(final String deleteFile, final ChannelSftp sftp) throws Exception {
- try {
- sftp.rm(deleteFile);
- } catch (Exception e) {
- exit(sftp);
- throw e;
- }
- }
- /**
- * 删除文件夹-sftp协议.
- * @param deleteFile 文件夹路径
- * @param sftp sftp连接
- * @throws Exception 异常
- */
- public static void rmDir(final String pathString, final ChannelSftp sftp) throws Exception {
- try {
- sftp.rmdir(pathString);
- } catch (Exception e) {
- exit(sftp);
- throw e;
- }
- }
- /**
- * 上传文件-sftp协议.
- * @param srcFile 源文件
- * @param dir 保存路径
- * @param fileName 保存文件名
- * @param sftp sftp连接
- * @throws Exception 异常
- */
- private static void uploadFile(final String srcFile, final String dir, final String fileName, final ChannelSftp sftp)
- throws Exception {
- mkdir(dir, sftp);
- sftp.cd(dir);
- sftp.put(srcFile, fileName);
- }
- /**
- * 上传文件-sftp协议.
- * @param srcFile 源文件路径,/xxx/xxx.zip 或 x:/xxx/xxx.zip;
- * @param sftp sftp连接
- * @throws Exception 异常
- */
- public static void uploadFile(final String srcFile, final ChannelSftp sftp) throws Exception {
- try {
- File file = new File(srcFile);
- if (file.exists()) {
- List<String> list = formatPath(srcFile);
- uploadFile(srcFile, list.get(0), list.get(1), sftp);
- }
- } catch (Exception e) {
- exit(sftp);
- throw e;
- }
- }
- /**
- * 根据路径创建文件夹.
- * @param dir 路径 必须是 /xxx/xxx/xxx/ 不能就单独一个/
- * @param sftp sftp连接
- * @throws Exception 异常
- */
- public static boolean mkdir(final String dir, final ChannelSftp sftp) throws Exception {
- try {
- if (StringUtils.isBlank(dir))
- return false;
- String md = dir.replaceAll("\\\\", "/");
- if (md.indexOf("/") != 0 || md.length() == 1)
- return false;
- return mkdirs(md, sftp);
- } catch (Exception e) {
- exit(sftp);
- throw e;
- }
- }
- /**
- * 递归创建文件夹.
- * @param dir 路径
- * @param sftp sftp连接
- * @return 是否创建成功
- * @throws SftpException 异常
- */
- private static boolean mkdirs(final String dir, final ChannelSftp sftp) throws SftpException {
- String dirs = dir.substring(1, dir.length() - 1);
- String[] dirArr = dirs.split("/");
- String base = "";
- for (String d : dirArr) {
- base += "/" + d;
- if (dirExist(base + "/", sftp)) {
- continue;
- } else {
- sftp.mkdir(base + "/");
- }
- }
- return true;
- }
- /**
- * 判断文件夹是否存在.
- * @param dir 文件夹路径, /xxx/xxx/
- * @param sftp sftp协议
- * @return 是否存在
- */
- public static boolean dirExist(final String dir, final ChannelSftp sftp) {
- try {
- Vector<?> vector = sftp.ls(dir);
- if (null == vector)
- return false;
- else
- return true;
- } catch (SftpException e) {
- return false;
- }
- }
- /**
- * 格式化路径.
- * @param srcPath 原路径. /xxx/xxx/xxx.yyy 或 X:/xxx/xxx/xxx.yy
- * @return list, 第一个是路径(/xxx/xxx/),第二个是文件名(xxx.yy)
- */
- public static List<String> formatPath(final String srcPath) {
- List<String> list = new ArrayList<String>(2);
- String dir = "";
- String fileName = "";
- String repSrc = srcPath.replaceAll("\\\\", "/");
- int firstP = repSrc.indexOf("/");
- int lastP = repSrc.lastIndexOf("/");
- fileName = repSrc.substring(lastP + 1);
- dir = repSrc.substring(firstP, lastP);
- dir = PRE_FIX + (dir.length() == 1 ? dir : (dir + "/"));
- list.add(dir);
- list.add(fileName);
- return list;
- }
- /**
- * 关闭协议-sftp协议.
- * @param sftp sftp连接
- */
- public static void exit(final ChannelSftp sftp) {
- sftp.exit();
- }
- public static void main(String[] args) throws Exception {
- ChannelSftp sftp = getSftpConnect("192.168.0.35", 22, "root", "root");
- String pathString = "C:\\test\\aaa\\Foxmail7.zip";
- File file = new File(pathString);
- System.out.println("上传文件开始...");
- uploadFile(pathString, sftp);
- System.out.println("上传成功,开始删除本地文件...");
- file.delete();
- System.out.println("删除完成,开始校验本地文件...");
- if (!file.exists()) {
- System.out.println("文件不存在,开始从远程服务器获取...");
- download(pathString, pathString, sftp);
- System.out.println("下载完成");
- } else {
- System.out.println("在本地找到文件");
- }
- exit(sftp);
- System.exit(0);
- }
- }
v0.2-新增sftp连接池
- /**
- * sftp连接池.
- */
- private static final Map<String, Channel> SFTP_CHANNEL_POOL = new HashMap<String, Channel>();
- /**
- * 获取sftp协议连接.
- * @param host 主机名
- * @param port 端口
- * @param username 用户名
- * @param password 密码
- * @return 连接对象
- * @throws JSchException 异常
- */
- public static ChannelSftp getSftpConnect(final String host, final int port, final String username,
- final String password) throws JSchException {
- Session sshSession = null;
- Channel channel = null;
- ChannelSftp sftp = null;
- String key = host + "," + port + "," + username + "," + password;
- if (null == SFTP_CHANNEL_POOL.get(key)) {
- JSch jsch = new JSch();
- jsch.getSession(username, host, port);
- sshSession = jsch.getSession(username, host, port);
- sshSession.setPassword(password);
- Properties sshConfig = new Properties();
- sshConfig.put("StrictHostKeyChecking", "no");
- sshSession.setConfig(sshConfig);
- sshSession.connect();
- channel = sshSession.openChannel("sftp");
- channel.connect();
- SFTP_CHANNEL_POOL.put(key, channel);
- } else {
- channel = SFTP_CHANNEL_POOL.get(key);
- sshSession = channel.getSession();
- if (!sshSession.isConnected())
- sshSession.connect();
- if (!channel.isConnected())
- channel.connect();
- }
- sftp = (ChannelSftp) channel;
- return sftp;
- }
v0.3-修改了一些bug,新增递归删除文件夹功能
- package com.noryar.filesystem.utils;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import java.util.Properties;
- import java.util.Vector;
- import org.apache.commons.lang.StringUtils;
- import com.jcraft.jsch.Channel;
- import com.jcraft.jsch.ChannelSftp;
- import com.jcraft.jsch.ChannelSftp.LsEntry;
- import com.jcraft.jsch.JSch;
- import com.jcraft.jsch.JSchException;
- import com.jcraft.jsch.Session;
- import com.jcraft.jsch.SftpException;
- /**
- * 文件工具类.<br>
- * 1.所有的文件路径必须以'/'开头和结尾,否则路径最后一部分会被当做是文件名<br>
- * 2.方法出现异常的时候,会关闭sftp连接(但是不会关闭session和channel),异常会抛出
- * @author Leon Lee
- */
- public class SftpUtil {
- /**
- * 文件路径前缀. /ddit-remote
- */
- private static final String PRE_FIX = "/test-noryar";
- /**
- * sftp连接池.
- */
- private static final Map<String, Channel> SFTP_CHANNEL_POOL = new HashMap<String, Channel>();
- /**
- * 获取sftp协议连接.
- * @param host 主机名
- * @param port 端口
- * @param username 用户名
- * @param password 密码
- * @return 连接对象
- * @throws JSchException 异常
- */
- public static ChannelSftp getSftpConnect(final String host, final int port, final String username,
- final String password) throws JSchException {
- Session sshSession = null;
- Channel channel = null;
- ChannelSftp sftp = null;
- String key = host + "," + port + "," + username + "," + password;
- if (null == SFTP_CHANNEL_POOL.get(key)) {
- JSch jsch = new JSch();
- jsch.getSession(username, host, port);
- sshSession = jsch.getSession(username, host, port);
- sshSession.setPassword(password);
- Properties sshConfig = new Properties();
- sshConfig.put("StrictHostKeyChecking", "no");
- sshSession.setConfig(sshConfig);
- sshSession.connect();
- channel = sshSession.openChannel("sftp");
- channel.connect();
- SFTP_CHANNEL_POOL.put(key, channel);
- } else {
- channel = SFTP_CHANNEL_POOL.get(key);
- sshSession = channel.getSession();
- if (!sshSession.isConnected())
- sshSession.connect();
- if (!channel.isConnected())
- channel.connect();
- }
- sftp = (ChannelSftp) channel;
- return sftp;
- }
- /**
- * 下载文件-sftp协议.
- * @param downloadFile 下载的文件
- * @param saveFile 存在本地的路径
- * @param sftp sftp连接
- * @return 文件
- * @throws Exception 异常
- */
- public static File download(final String downloadFile, final String saveFile, final ChannelSftp sftp)
- throws Exception {
- FileOutputStream os = null;
- File file = new File(saveFile);
- try {
- if (!file.exists()) {
- File parentFile = file.getParentFile();
- if (!parentFile.exists()) {
- parentFile.mkdirs();
- }
- file.createNewFile();
- }
- os = new FileOutputStream(file);
- List<String> list = formatPath(downloadFile);
- sftp.get(list.get(0) + list.get(1), os);
- } catch (Exception e) {
- exit(sftp);
- e.getMessage();
- throw e;
- } finally {
- os.close();
- }
- return file;
- }
- /**
- * 下载文件-sftp协议.
- * @param downloadFile 下载的文件
- * @param saveFile 存在本地的路径
- * @param sftp sftp连接
- * @return 文件 byte[]
- * @throws Exception 异常
- */
- public static byte[] downloadAsByte(final String downloadFile, final ChannelSftp sftp) throws Exception {
- ByteArrayOutputStream os = new ByteArrayOutputStream();
- try {
- List<String> list = formatPath(downloadFile);
- sftp.get(list.get(0) + list.get(1), os);
- } catch (Exception e) {
- exit(sftp);
- throw e;
- } finally {
- os.close();
- }
- return os.toByteArray();
- }
- /**
- * 删除文件-sftp协议.
- * @param pathString 要删除的文件
- * @param sftp sftp连接
- * @throws Exception 异常
- */
- public static void rmFile(final String pathString, final ChannelSftp sftp) throws Exception {
- try {
- List<String> list = formatPath(pathString);
- sftp.rm(list.get(0) + list.get(1));
- } catch (Exception e) {
- exit(sftp);
- throw e;
- }
- }
- /**
- * 删除文件夹-sftp协议.如果文件夹有内容,则会抛出异常.
- * @param pathString 文件夹路径
- * @param sftp sftp连接
- * @param resursion 递归删除
- * @throws Exception 异常
- */
- public static void rmDir(final String pathString, final ChannelSftp sftp, final boolean recursion) throws Exception {
- try {
- String fp = formatPath(pathString).get(0);
- if (recursion)
- exeRmRec(fp, sftp);
- else
- sftp.rmdir(fp);
- } catch (Exception e) {
- exit(sftp);
- throw e;
- }
- }
- /**
- * 递归删除执行.
- * @param pathString 文件路径
- * @param sftp sftp连接
- * @throws SftpException
- */
- private static void exeRmRec(final String pathString, final ChannelSftp sftp) throws SftpException {
- @SuppressWarnings("unchecked")
- Vector<LsEntry> vector = sftp.ls(pathString);
- if (vector.size() == 1) { // 文件,直接删除
- sftp.rm(pathString);
- } else if (vector.size() == 2) { // 空文件夹,直接删除
- sftp.rmdir(pathString);
- } else {
- String fileName = "";
- // 删除文件夹下所有文件
- for (LsEntry en : vector) {
- fileName = en.getFilename();
- if (".".equals(fileName) || "..".equals(fileName)) {
- continue;
- } else {
- exeRmRec(pathString + "/" + fileName, sftp);
- }
- }
- // 删除文件夹
- sftp.rmdir(pathString);
- }
- }
- /**
- * 上传文件-sftp协议.
- * @param srcFile 源文件
- * @param dir 保存路径
- * @param fileName 保存文件名
- * @param sftp sftp连接
- * @throws Exception 异常
- */
- private static void uploadFile(final String srcFile, final String dir, final String fileName, final ChannelSftp sftp)
- throws Exception {
- mkdir(dir, sftp);
- sftp.cd(dir);
- sftp.put(srcFile, fileName);
- }
- /**
- * 上传文件-sftp协议.
- * @param srcFile 源文件路径,/xxx/xx.yy 或 x:/xxx/xxx.yy
- * @param sftp sftp连接
- * @return 上传成功与否
- * @throws Exception 异常
- */
- public static boolean uploadFile(final String srcFile, final ChannelSftp sftp) throws Exception {
- try {
- File file = new File(srcFile);
- if (file.exists()) {
- List<String> list = formatPath(srcFile);
- uploadFile(srcFile, list.get(0), list.get(1), sftp);
- return true;
- }
- return false;
- } catch (Exception e) {
- exit(sftp);
- throw e;
- }
- }
- /**
- * 根据路径创建文件夹.
- * @param dir 路径 必须是 /xxx/xxx/ 不能就单独一个/
- * @param sftp sftp连接
- * @throws Exception 异常
- */
- public static boolean mkdir(final String dir, final ChannelSftp sftp) throws Exception {
- try {
- if (StringUtils.isBlank(dir))
- return false;
- String md = dir.replaceAll("\\\\", "/");
- if (md.indexOf("/") != 0 || md.length() == 1)
- return false;
- return mkdirs(md, sftp);
- } catch (Exception e) {
- exit(sftp);
- throw e;
- }
- }
- /**
- * 递归创建文件夹.
- * @param dir 路径
- * @param sftp sftp连接
- * @return 是否创建成功
- * @throws SftpException 异常
- */
- private static boolean mkdirs(final String dir, final ChannelSftp sftp) throws SftpException {
- String dirs = dir.substring(1, dir.length() - 1);
- String[] dirArr = dirs.split("/");
- String base = "";
- for (String d : dirArr) {
- base += "/" + d;
- if (dirExist(base + "/", sftp)) {
- continue;
- } else {
- sftp.mkdir(base + "/");
- }
- }
- return true;
- }
- /**
- * 判断文件夹是否存在.
- * @param dir 文件夹路径, /xxx/xxx/
- * @param sftp sftp协议
- * @return 是否存在
- */
- private static boolean dirExist(final String dir, final ChannelSftp sftp) {
- try {
- Vector<?> vector = sftp.ls(dir);
- if (null == vector)
- return false;
- else
- return true;
- } catch (SftpException e) {
- return false;
- }
- }
- /**
- * 格式化路径.
- * @param srcPath 原路径. /xxx/xxx/xxx.yyy 或 X:/xxx/xxx/xxx.yy
- * @return list, 第一个是路径(/xxx/xxx/),第二个是文件名(xxx.yy)
- */
- public static List<String> formatPath(final String srcPath) {
- List<String> list = new ArrayList<String>(2);
- String repSrc = srcPath.replaceAll("\\\\", "/");
- int firstP = repSrc.indexOf("/");
- int lastP = repSrc.lastIndexOf("/");
- String fileName = lastP + 1 == repSrc.length() ? "" : repSrc.substring(lastP + 1);
- String dir = firstP == -1 ? "" : repSrc.substring(firstP, lastP);
- dir = PRE_FIX + (dir.length() == 1 ? dir : (dir + "/"));
- list.add(dir);
- list.add(fileName);
- return list;
- }
- /**
- * 关闭协议-sftp协议.
- * @param sftp sftp连接
- */
- public static void exit(final ChannelSftp sftp) {
- sftp.exit();
- }
- public static void main(String[] args) throws Exception {
- ChannelSftp sftp = getSftpConnect("192.168.0.35", 22, "root", "root");
- // String pathString = "C:\\test\\ccc\\Foxmail7.zip";
- // File file = new File(pathString);
- // System.out.println("上传文件开始...");
- // uploadFile(pathString, sftp);
- // System.out.println("上传成功,开始删除本地文件...");
- // file.delete();
- // System.out.println("删除完成,开始校验本地文件...");
- // if (!file.exists()) {
- // System.out.println("文件不存在,开始从远程服务器获取...");
- // download(pathString, pathString, sftp);
- // System.out.println("下载完成");
- // } else {
- // System.out.println("在本地找到文件");
- // }
- rmDir("", sftp, true);
- exit(sftp);
- System.exit(0);
- }
- }
v0.31
- package com.noryar.filesystem.utils;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import java.util.Properties;
- import java.util.Vector;
- import org.apache.commons.lang.StringUtils;
- import com.jcraft.jsch.Channel;
- import com.jcraft.jsch.ChannelSftp;
- import com.jcraft.jsch.ChannelSftp.LsEntry;
- import com.jcraft.jsch.JSch;
- import com.jcraft.jsch.JSchException;
- import com.jcraft.jsch.Session;
- import com.jcraft.jsch.SftpException;
- /**
- * 文件工具类.<br>
- * 1.所有的文件路径必须以'/'开头和结尾,否则路径最后一部分会被当做是文件名<br>
- * 2. @since version-0.3 方法出现异常的时候,<del>会关闭sftp连接(但是不会关闭session和channel)</del>(del @ version 0.31),异常会抛出<br>
- * @author Leon Lee
- */
- public class SftpUtil {
- /**
- * 文件路径前缀. /ddit-remote
- */
- private static final String PRE_FIX = "/test-noryar";
- /**
- * sftp连接池.
- */
- private static final Map<String, Channel> SFTP_CHANNEL_POOL = new HashMap<String, Channel>();
- /**
- * 获取sftp协议连接.
- * @param host 主机名
- * @param port 端口
- * @param username 用户名
- * @param password 密码
- * @return 连接对象
- * @throws JSchException 异常
- */
- public static ChannelSftp getSftpConnect(final String host, final int port, final String username,
- final String password) throws JSchException {
- Session sshSession = null;
- Channel channel = null;
- ChannelSftp sftp = null;
- String key = host + "," + port + "," + username + "," + password;
- if (null == SFTP_CHANNEL_POOL.get(key)) {
- JSch jsch = new JSch();
- jsch.getSession(username, host, port);
- sshSession = jsch.getSession(username, host, port);
- sshSession.setPassword(password);
- Properties sshConfig = new Properties();
- sshConfig.put("StrictHostKeyChecking", "no");
- sshSession.setConfig(sshConfig);
- sshSession.connect();
- channel = sshSession.openChannel("sftp");
- channel.connect();
- SFTP_CHANNEL_POOL.put(key, channel);
- } else {
- channel = SFTP_CHANNEL_POOL.get(key);
- sshSession = channel.getSession();
- if (!sshSession.isConnected())
- sshSession.connect();
- if (!channel.isConnected())
- channel.connect();
- }
- sftp = (ChannelSftp) channel;
- return sftp;
- }
- /**
- * 下载文件-sftp协议.
- * @param downloadFile 下载的文件
- * @param saveFile 存在本地的路径
- * @param sftp sftp连接
- * @return 文件
- * @throws Exception 异常
- */
- public static File download(final String downloadFile, final String saveFile, final ChannelSftp sftp)
- throws Exception {
- FileOutputStream os = null;
- File file = new File(saveFile);
- try {
- if (!file.exists()) {
- File parentFile = file.getParentFile();
- if (!parentFile.exists()) {
- parentFile.mkdirs();
- }
- file.createNewFile();
- }
- os = new FileOutputStream(file);
- List<String> list = formatPath(downloadFile);
- sftp.get(list.get(0) + list.get(1), os);
- } catch (Exception e) {
- throw e;
- } finally {
- os.close();
- }
- return file;
- }
- /**
- * 下载文件-sftp协议.
- * @param downloadFile 下载的文件
- * @param saveFile 存在本地的路径
- * @param sftp sftp连接
- * @return 文件 byte[]
- * @throws Exception 异常
- */
- public static byte[] downloadAsByte(final String downloadFile, final ChannelSftp sftp) throws Exception {
- ByteArrayOutputStream os = new ByteArrayOutputStream();
- try {
- List<String> list = formatPath(downloadFile);
- sftp.get(list.get(0) + list.get(1), os);
- } catch (Exception e) {
- throw e;
- } finally {
- os.close();
- }
- return os.toByteArray();
- }
- /**
- * 删除文件-sftp协议.
- * @param pathString 要删除的文件
- * @param sftp sftp连接
- * @throws SftpException 异常
- */
- public static void rmFile(final String pathString, final ChannelSftp sftp) throws SftpException {
- List<String> list = formatPath(pathString);
- String dir = list.get(0);
- String file = list.get(1);
- if (dirExist(dir + file, sftp)) {
- sftp.rm(list.get(0) + list.get(1));
- }
- }
- /**
- * 删除文件夹-sftp协议.如果文件夹有内容,则会抛出异常.
- * @param pathString 文件夹路径
- * @param sftp sftp连接
- * @param resursion 递归删除
- * @throws SftpException 异常
- */
- public static void rmDir(final String pathString, final ChannelSftp sftp, final boolean recursion)
- throws SftpException {
- String fp = formatPath(pathString).get(0);
- if (dirExist(fp, sftp)) {
- if (recursion)
- exeRmRec(fp, sftp);
- else
- sftp.rmdir(fp);
- }
- }
- /**
- * 递归删除执行.
- * @param pathString 文件路径
- * @param sftp sftp连接
- * @throws SftpException
- */
- private static void exeRmRec(final String pathString, final ChannelSftp sftp) throws SftpException {
- @SuppressWarnings("unchecked")
- Vector<LsEntry> vector = sftp.ls(pathString);
- if (vector.size() == 1) { // 文件,直接删除
- sftp.rm(pathString);
- } else if (vector.size() == 2) { // 空文件夹,直接删除
- sftp.rmdir(pathString);
- } else {
- String fileName = "";
- // 删除文件夹下所有文件
- for (LsEntry en : vector) {
- fileName = en.getFilename();
- if (".".equals(fileName) || "..".equals(fileName)) {
- continue;
- } else {
- exeRmRec(pathString + "/" + fileName, sftp);
- }
- }
- // 删除文件夹
- sftp.rmdir(pathString);
- }
- }
- /**
- * 上传文件-sftp协议.
- * @param srcFile 源文件
- * @param dir 保存路径
- * @param fileName 保存文件名
- * @param sftp sftp连接
- * @throws Exception 异常
- */
- private static void uploadFile(final String srcFile, final String dir, final String fileName, final ChannelSftp sftp)
- throws SftpException {
- mkdir(dir, sftp);
- sftp.cd(dir);
- sftp.put(srcFile, fileName);
- }
- /**
- * 上传文件-sftp协议.
- * @param srcFile 源文件路径,/xxx/xx.yy 或 x:/xxx/xxx.yy
- * @param sftp sftp连接
- * @return 上传成功与否
- * @throws SftpException 异常
- */
- public static boolean uploadFile(final String srcFile, final ChannelSftp sftp) throws SftpException {
- File file = new File(srcFile);
- if (file.exists()) {
- List<String> list = formatPath(srcFile);
- uploadFile(srcFile, list.get(0), list.get(1), sftp);
- return true;
- }
- return false;
- }
- /**
- * 根据路径创建文件夹.
- * @param dir 路径 必须是 /xxx/xxx/ 不能就单独一个/
- * @param sftp sftp连接
- * @throws SftpException 异常
- */
- public static boolean mkdir(final String dir, final ChannelSftp sftp) throws SftpException {
- if (StringUtils.isBlank(dir))
- return false;
- String md = dir.replaceAll("\\\\", "/");
- if (md.indexOf("/") != 0 || md.length() == 1)
- return false;
- return mkdirs(md, sftp);
- }
- /**
- * 递归创建文件夹.
- * @param dir 路径
- * @param sftp sftp连接
- * @return 是否创建成功
- * @throws SftpException 异常
- */
- private static boolean mkdirs(final String dir, final ChannelSftp sftp) throws SftpException {
- String dirs = dir.substring(1, dir.length() - 1);
- String[] dirArr = dirs.split("/");
- String base = "";
- for (String d : dirArr) {
- base += "/" + d;
- if (dirExist(base + "/", sftp)) {
- continue;
- } else {
- sftp.mkdir(base + "/");
- }
- }
- return true;
- }
- /**
- * 判断文件夹是否存在.
- * @param dir 文件夹路径, /xxx/xxx/
- * @param sftp sftp协议
- * @return 是否存在
- */
- private static boolean dirExist(final String dir, final ChannelSftp sftp) {
- try {
- Vector<?> vector = sftp.ls(dir);
- if (null == vector)
- return false;
- else
- return true;
- } catch (SftpException e) {
- return false;
- }
- }
- /**
- * 格式化路径.
- * @param srcPath 原路径. /xxx/xxx/xxx.yyy 或 X:/xxx/xxx/xxx.yy
- * @return list, 第一个是路径(/xxx/xxx/),第二个是文件名(xxx.yy)
- */
- public static List<String> formatPath(final String srcPath) {
- List<String> list = new ArrayList<String>(2);
- String repSrc = srcPath.replaceAll("\\\\", "/");
- int firstP = repSrc.indexOf("/");
- int lastP = repSrc.lastIndexOf("/");
- String fileName = lastP + 1 == repSrc.length() ? "" : repSrc.substring(lastP + 1);
- String dir = firstP == -1 ? "" : repSrc.substring(firstP, lastP);
- dir = PRE_FIX + (dir.length() == 1 ? dir : (dir + "/"));
- list.add(dir);
- list.add(fileName);
- return list;
- }
- /**
- * 关闭协议-sftp协议.(关闭会导致连接池异常,因此不建议用户自定义关闭)
- * @param sftp sftp连接
- */
- private static void exit(final ChannelSftp sftp) {
- sftp.exit();
- }
- public static void main(String[] args) throws Exception {
- ChannelSftp sftp = getSftpConnect("192.168.0.35", 22, "root", "root");
- // String pathString = "C:\\test\\ccc\\Foxmail7.zip";
- // File file = new File(pathString);
- // System.out.println("上传文件开始...");
- // uploadFile(pathString, sftp);
- // System.out.println("上传成功,开始删除本地文件...");
- // file.delete();
- // System.out.println("删除完成,开始校验本地文件...");
- // if (!file.exists()) {
- // System.out.println("文件不存在,开始从远程服务器获取...");
- // download(pathString, pathString, sftp);
- // System.out.println("下载完成");
- // } else {
- // System.out.println("在本地找到文件");
- // }
- // rmDir("", sftp, true);
- String path = "E:\\aaa.zip";
- File file = SftpUtil.download(path, path, sftp);
- // SftpUtil.exit(sftp);
- exit(sftp);
- System.exit(0);
- }
- }
转载于:https://www.cnblogs.com/ceshi2016/p/7519788.html
文件系统之-JAVA Sftp远程操作:相关推荐
- 在Eclipse中运行JAVA代码远程操作HBase的示例
2019独角兽企业重金招聘Python工程师标准>>> 下面是一个在Windows的Eclipse中通过JAVA操作一个Linux上运行的hbase的示例. Hbase的配置需要注意 ...
- java使用Jsch实现远程操作linux服务器进行文件上传、下载,删除和显示目录信息...
1.java使用Jsch实现远程操作linux服务器进行文件上传.下载,删除和显示目录信息. 参考链接:https://www.cnblogs.com/longyg/archive/2012/06/2 ...
- Java网页数据采集器[续篇-远程操作]
本期概述 上期我们学习了html页面采集后的数据查询, 但这仅仅是在本地查询数据库,如果我们想通过远程操作来进行数据的采集,存储和查询,那又该怎么做呢? 今天我们一起来学习下:如何通过本地客户端远程访 ...
- JSch:Java Secure Channel -- java 代码实现 ssh 远程操作
前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家.点击跳转到教程. JSch 是SSH2的一个纯Java实现. 它允许你连接到一个 sshd 服务器,使用端口转发,X1 ...
- java读取文件服务器文件,java读取远程服务器文件
java读取远程服务器文件 内容精选 换一换 已成功登录Java性能分析.待安装Guardian的服务器已开启sshd.待安装Guardian的服务器已安装JRE,JRE版本要求为Huawei JDK ...
- 5.WEB及远程操作
WEB及远程操作 1.Spring MVC总结 1.1 Spring MVC 框架请求处理流程 1.2 Spring MVC框架包含内容 1.3 Spring MVC 核心 1.3.1 Dispatc ...
- java 跨服务器 文件拷贝,java拷贝远程服务器上文件
java拷贝远程服务器上文件 内容精选 换一换 已成功登录Java性能分析.待安装Guardian的服务器已开启sshd.待安装Guardian的服务器已安装JRE,JRE版本要求为Huawei JD ...
- java读远程服务器文件,java 读取远程服务器文件
java 读取远程服务器文件 [2021-01-31 12:09:45] 简介: php去除nbsp的方法:首先创建一个PHP代码示例文件:然后通过"preg_replace(" ...
- 关于Hadoop多用户管理支持客户端远程操作的理论总结
1.问题 Hadoop客户端如何配置可远程操作Hadoop:Hadoop多用户情况下,是如何管理权限并分配存储空间和计算能力,保证集群的稳定. 2.Hadoop平台 要理解客户端如何通过指定用户远程操 ...
最新文章
- 混合mixin函数_Less 混合
- 真香!一行Python代码,帮你制作小姐姐的表情包,靠谱吗?
- SAP Webclient UI和Fiori UI的混搭
- Android之提示android.content.res.Resources$NotFoundException: Resource ID #0x7f08010a
- c#中textbox属性_C#.Net中的TextBox.MaxLength属性与示例
- cemtos7上mysql8两个实例_centos7上配置mysql8的双主互写
- java实验检查危险品代码_2019JAVA第六次实验报告
- Activity生命周期(二)
- python excel 提取特定行_Python之从Excel一列内提取数字
- 尚硅谷python全套-尚硅谷Java视频教程,粉丝无数,人手一套尚硅谷教程
- python装饰器两层和三层_2020 python学习第十六天————三层装饰器与迭代器
- 转载 《TypeScript 类型定义 DefinitelyTyped》
- python选择时间窗口_对pandas中时间窗函数rolling的使用详解
- 教你如何轻松玩转自媒体淘客,赚大钱!
- 机器学习方法的基本分类
- struct字节计算
- leetcode46题 php实现,Leetcode PHP题解--D46 893. Groups of Special-Equivalent Strings
- 《深入理解Java虚拟机》内存管理机制 部分 读书笔记
- 数学建模学习1.22——多元回归分析
- [Unity Mirror] Network Discovery