一、sftp和ftp比较(借鉴:http://www.cnblogs.com/xuliangxing/p/7120130.html):
1.适用场景:
我们平时习惯了使用ftp来上传下载文件,尤其是很多Linux环境下,我们一般都会通过第三方的SSH工具连接到Linux,但是当我们需要传输文件到Linux服务器当中,很多人习惯用ftp来传输,其实Linux默认是不提供ftp的,需要你额外安装FTP服务器。而且ftp服务器端会占用一定的VPS服务器资源。
2.其实笔者更建议使用sftp代替ftp,主要原因:
3.主要区别:
FTP是一种文件传输协议,一般是为了方便数据共享的。包括一个FTP服务器和多个FTP客户端。FTP客户端通过FTP协议在服务器上下载资源。而SFTP协议是在FTP的基础上对数据进行加密,使得传输的数据相对来说更安全。但是这种安全是以牺牲效率为代价的,也就是说SFTP的传输效率比FTP要低(不过现实使用当中,没有发现多大差别)。个人肤浅的认为就是:一;FTP要安装,SFTP不要安装。二;SFTP更安全,但更安全带来副作用就是的效率比FTP要低些。
二、FtpUtil .java
package com.lmp.utils; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ssl.DefaultHostnameVerifier; import org.apache.http.conn.util.PublicSuffixMatcher; import org.apache.http.conn.util.PublicSuffixMatcherLoader; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.CharsetUtils; import org.apache.http.util.EntityUtils; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; public class FtpUtil {
private RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000) .setConnectionRequestTimeout(15000).build(); // 单例模式 private static FtpUtil instance = null; private FtpUtil() {
} public static FtpUtil getInstance() {
if (instance == null) {
instance = new FtpUtil(); } return instance; } / * 发送 post请求 * * @param httpUrl 地址 */ public String sendHttpPost(String httpUrl) {
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost return sendHttpPost(httpPost); } / * 发送 post请求 * * @param httpUrl 地址 * @param params 参数(格式:key1=value1&key2=value2) */ public String sendHttpPost(String httpUrl, String params) {
HttpPost httpPost = new HttpPost(httpUrl); try {
StringEntity stringEntity = new StringEntity(params, "UTF-9=8"); stringEntity.setContentType("application/x-www-form-urlencoded"); httpPost.setEntity(stringEntity); } catch (Exception e) {
e.printStackTrace(); } return sendHttpPost(httpPost); } / * 发送 post请求 * * @param httpUrl 地址 * @param maps 参数 */ public String sendHttpPost(String httpUrl, Map<String, String> maps) {
HttpPost httpPost = new HttpPost(httpUrl); // 创建参数队列 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); for (String key : maps.keySet()) {
nameValuePairs.add(new BasicNameValuePair(key, maps.get(key))); } try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); } catch (Exception e) {
e.printStackTrace(); } return sendHttpPost(httpPost); } / * 发送 post请求(带文件) * * @param httpUrl 地址 * @param maps 参数 * @param fileLists 附件 */ public String sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists) {
HttpPost httpPost = new HttpPost(httpUrl); MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create(); for (String key : maps.keySet()) {
meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN)); } for (File file : fileLists) {
FileBody fileBody = new FileBody(file); meBuilder.addPart("files", fileBody); } HttpEntity reqEntity = meBuilder.build(); httpPost.setEntity(reqEntity); return sendHttpPost(httpPost); } / * 发送Post请求 * * @param httpPost * @return */ private String sendHttpPost(HttpPost httpPost) {
CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; HttpEntity entity = null; String responseContent = null; try {
// 创建默认的httpClient实例 httpClient = HttpClients.createDefault(); httpPost.setConfig(requestConfig); // 执行请求 response = httpClient.execute(httpPost); entity = response.getEntity(); responseContent = EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) {
e.printStackTrace(); } finally {
try {
if (response != null) {
response.close(); } if (httpClient != null) {
httpClient.close(); } } catch (Exception e2) {
e2.printStackTrace(); } } return responseContent; } / * 发送 post请求 * * @param httpUrl 地址 * @param json 参数 */ public String sendJsonHttpPostString(String httpUrl, String json) {
CloseableHttpClient httpclient = HttpClients.createDefault(); String responseInfo = null; try {
HttpPost httpPost = new HttpPost(httpUrl); httpPost.addHeader("Content-Type", "application/json;charset=UTF-8"); ContentType contentType = ContentType.create("application/json", CharsetUtils.get("UTF-8")); httpPost.setEntity(new StringEntity(json, contentType)); CloseableHttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) {
if (null != entity) {
responseInfo = EntityUtils.toString(entity); responseInfo = new String(responseInfo.getBytes("ISO-8859-1"), "UTF-8"); } } } catch (Exception e) {
e.printStackTrace(); } finally {
try {
httpclient.close(); } catch (IOException e) {
e.printStackTrace(); } } return responseInfo; } / * 发送 post请求 * * @param httpUrl 地址 * @param json 参数 */ public String sendJsonHttpPost(String httpUrl, String json) {
CloseableHttpClient httpclient = HttpClients.createDefault(); String responseInfo = null; try {
HttpPost httpPost = new HttpPost(httpUrl); httpPost.addHeader("Content-Type", "application/json;charset=UTF-8"); ContentType contentType = ContentType.create("application/json", CharsetUtils.get("UTF-8")); httpPost.setEntity(new StringEntity(json, contentType)); CloseableHttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) {
if (null != entity) {
responseInfo = EntityUtils.toString(entity); responseInfo = new String(responseInfo.getBytes("ISO-8859-1"), "UTF-8"); } }else{
return responseInfo; } } catch (Exception e) {
e.printStackTrace(); } finally {
try {
httpclient.close(); } catch (IOException e) {
e.printStackTrace(); } } return responseInfo; } / * 发送 post请求(multipart/form-data) * * @param httpUrl 地址 * @param file 参数 */ public String sendFileHttpPost(String httpUrl, File file) {
CloseableHttpClient httpclient = HttpClients.createDefault(); String responseInfo = null; try {
HttpPost httpPost = new HttpPost(httpUrl); //把文件转换成流对象FileBody FileBody bin = new FileBody(file); HttpEntity reqEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addPart("file", bin)//相当于 .setContentType(ContentType.create("multipart/form-data", CharsetUtils.get("UTF-8"))) .build(); httpPost.setEntity(reqEntity); CloseableHttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) {
if (null != entity) {
responseInfo = EntityUtils.toString(entity); responseInfo = new String(responseInfo.getBytes("ISO-8859-1"), "UTF-8"); } } } catch (Exception e) {
e.printStackTrace(); } finally {
try {
httpclient.close(); } catch (IOException e) {
e.printStackTrace(); } } return responseInfo; } / * 发送 post请求(multipart/form-data) * * @param httpUrl 地址 * @param file 参数 */ public String sendFileAndMapHttpPost(String httpUrl, Map<String, String> maps, File file) {
HttpPost httpPost = new HttpPost(httpUrl); MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create(); for (String key : maps.keySet()) {
if(maps.get(key)==null){
continue; } meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.MULTIPART_FORM_DATA)); } FileBody fileBody = new FileBody(file); meBuilder.addPart("file", fileBody); HttpEntity reqEntity = meBuilder.build(); httpPost.setEntity(reqEntity); return sendHttpPost(httpPost); } / * 发送 get请求 * * @param httpUrl */ public String sendHttpGet(String httpUrl) {
HttpGet httpGet = new HttpGet(httpUrl); return sendHttpGet(httpGet); } / * 发送 get请求Https * * @param httpUrl */ public String sendHttpsGet(String httpUrl) {
HttpGet httpGet = new HttpGet(httpUrl); return sendHttpGet(httpGet); } / * 发送Get请求 * * @param httpGet * @return */ public String sendHttpGet(HttpGet httpGet) {
CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; HttpEntity entity = null; String responseContent = null; try {
// 创建默认的httpClient实例 httpClient = HttpClients.createDefault(); httpGet.setConfig(requestConfig); // 执行请求 response = httpClient.execute(httpGet); entity = response.getEntity(); responseContent = EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) {
e.printStackTrace(); } finally {
try {
if (response != null) {
response.close(); } if (httpClient != null) {
httpClient.close(); } } catch (Exception e2) {
e2.printStackTrace(); } } return responseContent; } / * 发送Get请求Https * * @param httpGet * @return */ private String sendHttpsGet(HttpGet httpGet) {
CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; HttpEntity entity = null; String responseContent = null; try {
// 创建默认的httpClient实例 PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader .load(new URL(httpGet.getURI().toString())); DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher); httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build(); httpGet.setConfig(requestConfig); // 执行请求 response = httpClient.execute(httpGet); entity = response.getEntity(); responseContent = EntityUtils.toString(entity, "UTF-8"); } catch (Exception e) {
e.printStackTrace(); } finally {
try {
if (response != null) {
response.close(); } if (httpClient != null) {
httpClient.close(); } } catch (Exception e2) {
e2.printStackTrace(); } } return responseContent; } public static void main (String args[]){
Map map = new HashMap<>(); map.put("param1","222"); map.put("param2","333"); String httpUrl = "http://..."; String result = HttpClientUtil.getInstance().sendJsonHttpPost(httpUrl, GsonUtil.toJsonString(map)); System.out.println(result); } }
三、SftpUtil.java
package com.lmp.utils; 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.SftpATTRS; import com.jcraft.jsch.SftpException; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.Vector; / * Sftp调用罗氏文件服务器工具类 * * @version 1.0 */ public class SftpUtil {
public static final String ROCHE_SFTP_URL = "127.0.0.1"; public static final int ROCHE_SFTP_PORT = 22; public static final String ROCHE_SFTP_USERNAME = "administrator"; public static final String ROCHE_SFTP_PASSWORD = "admin"; / * jcraft的ChannelSftp类实例,信息传输通道 */ private ChannelSftp channelSftp; / * jcraft的session类实例,用来持久化连接 */ private Session session; / * 当前操作路径 */ private String currentPath; / * 当前目录下文件列表 */ private Vector currentFiles; / * 取得当前的ChannelSftp实例 * * @return 当前的ChannelSftp实例 */ public ChannelSftp getChannelSftp() {
return channelSftp; } / * 根据指定config相关信息,连接远程sftp服务器 */ public void connectServer() {
String server = ROCHE_SFTP_URL; int port = ROCHE_SFTP_PORT; String username = ROCHE_SFTP_USERNAME; String password = ROCHE_SFTP_PASSWORD; String location = "/"; String encode = ""; connectServer(server, port, username, password, location, encode); } / * 链接远程ftp服务器 * * @param server 服务器地址 * @param port 服务器端口 * @param user 用户名 * @param password 密码 * @param path 登陆后的默认路径 * @param encode 服务器文件系统编码 */ public void connectServer(String server, int port, String user, String password, String path, String encode) {
String errorMsg = ""; try {
JSch jsch = new JSch(); session = jsch.getSession(user, server, port); session.setPassword(password); // session.setUserInfo(new SftpUserInfo(ftpPassword)); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); session.setConfig(sshConfig); session.connect(); channelSftp = (ChannelSftp) session.openChannel("sftp"); channelSftp.connect(); if (encode != null && !"".equals(encode)) {
channelSftp.setFilenameEncoding(encode); } currentPath = channelSftp.getHome(); } catch (SftpException e) {
errorMsg = "无法使用SFTP传输文件!"; e.printStackTrace(); throw new RuntimeException(errorMsg); } catch (JSchException e) {
errorMsg = "没有权限与SFTP服务器连接!"; e.printStackTrace(); throw new RuntimeException(errorMsg); } } / * 内部方法,关闭OutputStream * * @param os 希望关闭的OutputStream */ private void closeOutputStream(OutputStream os) {
try {
if (null != os) {
os.close(); } } catch (IOException e) {
throw new RuntimeException("关闭OutputStream时出现异常:" + e.getMessage()); } } / * 内部方法,关闭InputStream * * @param is 希望关闭的InputStream */ private void closeInputStream(InputStream is) {
try {
if (null != is) {
is.close(); } } catch (IOException e) {
throw new RuntimeException("关闭OutputStream时出现异常:" + e.getMessage()); } } / * 内部方法,取得当前操作目录下的全部文件列表 */ public Vector getCurrentFileList() {
try {
Vector v = channelSftp.ls(currentPath); this.currentFiles = v; } catch (SftpException e) {
e.printStackTrace(); } return this.currentFiles; } / * 内部方法,获得操作路径 * * @param path 参数 * @return String */ private String getOperationPath(String path) {
String operactePath; if (!"".equals(path.trim()) && '/' == path.charAt(0)) {
operactePath = path; } else {
operactePath = currentPath + path; } if (operactePath.lastIndexOf("/") != operactePath.length() - 1) {
operactePath = operactePath + "/"; } return operactePath; } / * 内部方法,获得操作路径 * * @param path 参数 * @return String */ private String getFileOperationPath(String path) {
String operactePath; if ('/' == path.charAt(0)) {
operactePath = path; } else {
operactePath = currentPath + "/" + path; } return operactePath; } / * 内部方法,验证路径和sftp连接 * * @param path 路径 * @return 验证结果 */ private boolean dirValidation(String path) {
boolean result = true; if (channelSftp == null || !channelSftp.isConnected()) {
result = false; throw new RuntimeException("操作出现异常:channelSftp连接未创建"); } if (null != path && "".equals(path)) {
result = false; throw new RuntimeException("操作出现异常:指定的path不能为空"); } return result; } / * 内部方法,判断一个字符串,是文件路径 * * @param path 路径字符串 * @return 判断结果,是返回ture,否则false */ private boolean isFilePath(String path) {
boolean result = false; if (null != path && !"".equals(path) && path.lastIndexOf("/") < path.length()) {
result = true; } return result; } / * 变换当前目录 * * @param path 希望进入的目录 * @return 成功为true,失败返回false */ public boolean changeDir(String path) {
boolean result = false; if (dirValidation(path)) {
String testPath = getOperationPath(path); try {
channelSftp.cd(testPath); this.currentPath = testPath; result = true; } catch (SftpException e) {
throw new RuntimeException("变换目录'" + path + "'时发生错误:" + e.getMessage()); } } return result; } / * 创建目录 * * @param remotePath 远程目录 * @return 操作结果,成功为true,失败为false */ public boolean makeDir(String remotePath) {
boolean result = false; if (dirValidation(remotePath)) {
String testPath = getOperationPath(remotePath); try {
channelSftp.mkdir(testPath); result = true; } catch (SftpException e) {
throw new RuntimeException("创建目录'" + remotePath + "'时发生错误:" + e.getMessage()); } } return result; } / * 创建多级目录 * * @param pathName 相对路径 * @return * @throws IOException */ public boolean createDirectories(String pathName) throws IOException {
int flag = 0; String[] paths = pathName.split("/"); for (String p : paths) {
if (!changeDir(p)) {
if (makeDir(p)) {
if (changeDir(p)) {
flag += 1; } } } else {
flag += 1; } } if (flag == paths.length) {
return true; } return false; } / * 删除远程服务器上的目录(仅可删除非空目录) * * @param remotePath 远程目录 * @return 操作结果,成功为true,失败为false */ public boolean removeDir(String remotePath) {
boolean result = false; if (dirValidation(remotePath)) {
String testPath = getOperationPath(remotePath); try {
channelSftp.rmdir(testPath); result = true; } catch (SftpException e) {
throw new RuntimeException("删除目录'" + remotePath + "'时发生错误:" + e.getMessage()); } } return result; } / * 判断目录是否存在 * * @param remoteDirPath * @return */ public boolean existDir(String remoteDirPath) {
boolean result = false; if (dirValidation(remoteDirPath)) {
try {
this.channelSftp.cd(remoteDirPath); result = true; } catch (SftpException sException) {
if (ChannelSftp.SSH_FX_NO_SUCH_FILE == sException.id) {
System.out.println("目录不存在:" + remoteDirPath); } } } return result; } / * 内部方法,取得一个文件他所属的目录的路径 * * @param path 文件路径 * @return 判断结果,是返回ture,否则false */ private String getFileDir(String path) {
String result = ""; if (path.lastIndexOf("/") >= 0) {
result = path.substring(0, path.lastIndexOf("/")); } return result; } / * 内部方法,取得一个文件的文件名 * * @param path 文件路径 * @return 判断结果,是返回ture,否则false */ public String getFileName(String path) {
String result = path; if (path.lastIndexOf("/") > -1) {
result = path.substring(path.lastIndexOf("/") + 1, path.length()); } return result; } / * 判断文件是否存在 * * @param remoteFilePath 文件路径 * @return 文件存在,则返回true,否则返回false */ public boolean existFile(String remoteFilePath) {
boolean result = false; if (dirValidation(remoteFilePath)) {
if (!this.isFilePath(remoteFilePath)) {
throw new RuntimeException("这不是一个文件路径:" + remoteFilePath); } String pathDir = this.getFileDir(remoteFilePath); String realPathDir = this.getOperationPath(pathDir); String fileName = this.getFileName(remoteFilePath); try {
Vector v = channelSftp.ls(realPathDir); if (null != v && v.size() > 0) {
for (int i = 0; i < v.size(); ++i) {
LsEntry e = (LsEntry) v.get(i); if (e.getFilename().equals(fileName)) {
result = true; break; } } } } catch (SftpException e1) {
e1.printStackTrace(); } } return result; } / * 取得当前操作路径下的文件名列表(含文件夹) * * @return 文件名列表 */ public List<String> getFileList() {
this.getCurrentFileList(); List<String> result = null; if (null != currentFiles && currentFiles.size() > 0) {
result = new ArrayList<String>(); for (int i = 0; i < currentFiles.size(); ++i) {
result.add(((LsEntry) currentFiles.get(i)).getFilename()); } } return result; } / * 从SFTP服务器下载文件至本地 * * @param remoteFilePath 远程文件路径 * @param localFilePath 本地文件路径 * @return boolean */ public boolean downloadFile(String remoteFilePath, String localFilePath) {
if (dirValidation(remoteFilePath)) {
if (!existFile(remoteFilePath)) {
throw new RuntimeException("下载文件" + remoteFilePath + "时发生异常,远程文件并不存在"); } OutputStream os = null; try {
String realPath = getFileOperationPath(remoteFilePath); File file = new File(localFilePath); FileOutputStream fos = new FileOutputStream(file); // 从服务器下载文件到本地 channelSftp.get(realPath, fos); this.getCurrentFileList(); return true; } catch (IOException e) {
throw new RuntimeException("下载文件:" + remoteFilePath + "时发生文件读写错误:" + e.getMessage()); } catch (SftpException e) {
throw new RuntimeException("下载文件:" + remoteFilePath + "时发生Sftp错误:" + e.getMessage()); } finally {
this.closeOutputStream(os); } } else {
return false; } } / * 删除服务器上的文件 * * @param remoteFilePath 远程文件的完整路径 * @return 操作结果(boolean型) */ public boolean deleteFile(String remoteFilePath) {
if (dirValidation(remoteFilePath)) {
if (!existFile(remoteFilePath)) {
throw new RuntimeException("删除文件" + remoteFilePath + "时发生异常,远程文件并不存在"); } try {
String realPath = getFileOperationPath(remoteFilePath); channelSftp.rm(realPath); return true; } catch (SftpException e) {
throw new RuntimeException("删除文件:" + remoteFilePath + "时发生错误:" + e.getMessage()); } } else {
return false; } } / * 上传文件 * * @param remoteFilePath 远程文件名 remoteFilePath = 远程目录+文件名 * @param localFilepath 本地文件名 * @return -1 文件不存在 -2 文件内容为空 >0 成功上传,返回文件的大小 */ @SuppressWarnings("finally") public long upload(String remoteFilePath, String remoteFileName, String localFilepath) {
if (channelSftp == null || !channelSftp.isConnected()) {
throw new RuntimeException("上传文件" + localFilepath + "时发生异常,channelSftp连接未创建"); } InputStream is = null; long result = -1; try {
java.io.File fileIn = new java.io.File(localFilepath); if (fileIn.exists()) {
is = new FileInputStream(fileIn); result = fileIn.length(); //判断文件夹是否存在,不存在则创建文件夹 try {
createDir(remoteFilePath); } catch (Exception e) {
throw new RuntimeException("创建文件夹:" + remoteFilePath + "时发生错误:" + e.getMessage()); } channelSftp.cd(remoteFilePath); // 从本地上传到服务器 channelSftp.put(is, remoteFileName); } else {
result = -1; } } catch (IOException e) {
result = -1; throw new RuntimeException(e.getMessage() + ": 上传文件时发生错误!"); } catch (SftpException e) {
throw new RuntimeException(e.getMessage() + ": 上传文件时发生错误!"); } finally {
closeInputStream(is); } return result; } / * 上传文件 * * @param remoteFilePath 远程文件名 这个remoteFilePath = 远程目录+文件名 * @return -1 文件不存在 -2 文件内容为空 >0 成功上传,返回文件的大小 */ @SuppressWarnings("finally") public long upload(String remoteFilePath, String remoteFileName, InputStream is) {
if (channelSftp == null || !channelSftp.isConnected()) {
throw new RuntimeException("上传文件时发生异常,channelSftp连接未创建"); } long result = -1; try {
//判断文件夹是否存在,不存在则创建文件夹 try {
createDir(remoteFilePath); } catch (Exception e) {
throw new RuntimeException("创建文件夹:" + remoteFilePath + "时发生错误:" + e.getMessage()); } channelSftp.cd(remoteFilePath); // 从本地上传到服务器 channelSftp.put(is, remoteFileName); } catch (SftpException e) {
throw new RuntimeException(e.getMessage() + ": 上传文件时发生错误!"); } finally {
closeInputStream(is); } return result; } / * 上传文件 * * @param remoteFilePath 服务器文件夹 * @param filename 文面名 * @return 操作结果 */ public long upload(String remoteFilePath, String filename) {
String newname = ""; if (filename.lastIndexOf("/") > -1) {
newname = filename.substring(filename.lastIndexOf("/") + 1, filename.length()); } else {
newname = filename; } return upload(remoteFilePath, newname, filename); } / * 创建一个文件目录 */ public void createDir(String createpath) {
try {
if (isDirExist(createpath)) {
channelSftp.cd(createpath); } String pathArry[] = createpath.split("/"); StringBuffer filePath = new StringBuffer("/"); for (String path : pathArry) {
if (path.equals("")) {
continue; } filePath.append(path + "/"); if (isDirExist(filePath.toString())) {
channelSftp.cd(filePath.toString()); } else {
// 建立目录 channelSftp.mkdir(filePath.toString()); // 进入并设置为当前目录 channelSftp.cd(filePath.toString()); } } channelSftp.cd(createpath); } catch (SftpException e) {
throw new RuntimeException(e.getMessage() + ": 创建" + createpath + "文件夹发生错误!"); } } / * 判断目录是否存在 * * @param path * @return */ public boolean isDirExist(String path) {
boolean isExist = false; try {
SftpATTRS sftpATTRS = channelSftp.lstat(path); isExist = true; return sftpATTRS.isDir(); } catch (Exception e) {
if (e.getMessage().toLowerCase().equals("no such file")) {
isExist = false; } } return isExist; } / * 关闭连接 */ public void closeConnection() {
if (channelSftp != null) {
if (channelSftp.isConnected()) {
channelSftp.disconnect(); session.disconnect(); } } } public static void main(String args[]){
//测试上传 SftpUtil sftp1 = new SftpUtil(); sftp1.connectServer(); sftp1.upload("/test_2021/test_05/test_29/","C:/Users/HUAWEI/Desktop/upload.pdf"); sftp1.closeConnection(); //测试下载 SftpUtil sftp2 = new SftpUtil(); sftp2.connectServer(); sftp2.downloadFile("/test_2021/test_05/test_29/upload.pdf","C:/Users/HUAWEI/Desktop/download.pdf"); sftp2.closeConnection(); } }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/224535.html原文链接:https://javaforall.net
