sftp和ftp比较和应用

sftp和ftp比较和应用一 FtpUtil javapackagec lmp utils importorg apache http HttpEntity importorg apache http NameValuePai importorg apache http client config RequestConfi importorg apache http client entity UrlEncodedFo importorg apache http client me

一、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

(0)
上一篇 2026年3月17日 上午11:43
下一篇 2026年3月17日 上午11:43


相关推荐

  • openclaw 彻底卸载完整指南(2026)

    openclaw 彻底卸载完整指南(2026)

    2026年3月13日
    3
  • pytest执行多个用例_pytest如何循环执行用例

    pytest执行多个用例_pytest如何循环执行用例前言平常在做功能测试的时候,经常会遇到某个模块不稳定,偶然会出现一些bug,对于这种问题我们会针对此用例反复执行多次,最终复现出问题来。自动化运行用例时候,也会出现偶然的bug,可以针对单个用例,

    2022年7月30日
    8
  • Java和JavaScript区别与联系

    Java和JavaScript区别与联系Java和JavaScript有啥区别,据说还有很多人不知道,来给大家科普一下两者区别!Java和JavaScript不同之处:1.用处不一样:它们最本质的不同就是用途:Java目前被广泛应用于PC端、手机端、互联网、数据中心等等;而JavaScript则被主要用于嵌入文本到HTML页面,读写HTML元素,控制cookies等。2.出身不同:Javascript与…

    2022年7月8日
    22
  • Swift3创建数组

    Swift3创建数组数组是由一组类型相同的元素构成的有序数据集合。数组中的集合元素是有序的,而且可以重复出现。1 数组创建在Swift语言中,数组的类型格式为:Array或[ElementType]其中Array中的ElementType表示数组的类型,是泛型写法。[ElementType]是一种简写方式。两者表示的功能是一样的,我们更偏向于使用简写形式,本书里所有数组类型都是使用简写形式。下

    2022年5月27日
    45
  • P2P建立加密通道

    P2P建立加密通道核心:DH秘钥交互算法DH算法:对于非对称加密算法部分支持DH算法(spec256K1、curv25519、ed25519不支持但可以转换到curv25519间接实现),PrivA+PubB=PrivB+PubA,算法在公开双方公钥时就可使用各自保存的私钥,进行秘钥的交换;加密随机种子:随机生成nonce值,使用该nonce值以及交换过的秘钥对数据进行加密,nonce值附加到密文头部…

    2022年5月10日
    65
  • 我的世界怎么设置传送点指令_我的世界手机版领地指令

    我的世界怎么设置传送点指令_我的世界手机版领地指令今天小编为玩家们带来了我的世界服务器领地指令_我的世界地皮指令大全,希望对玩家们有所帮助,还不了解的玩家快来看看吧。圈地指令用木棍(各个服务器不一样,绝大部分默认是木锄)左击一个点,右击一个点(两点内为你想圈的长宽高,对角,一个高点,一个低点。)然后输查询大小,在输入创建领地。查询区域大小/resselectsize创建领地/rescreate名字移除领地/resremove名字领地转赠/resg…

    2025年11月27日
    4

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号