FTP SFTP工具类

FTP

package cn.greatlife.wechat.util;

import cn.greatlife.wechat.common.config.FtpConfig;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

/**
 * Ftp操作工具类
 * @date 2019-11-20
 * @author XXX
 * @version 1.0
 *
 */
public class FtpUtil {

    /**
     * apache的FTPClient,本工具类主要根据它,进行封装
     */
    private FTPClient ftpClient;

    /**
     * 数据类型:二进制数据
     */
    public static final int BINARY_FILE_TYPE = FTP.BINARY_FILE_TYPE;

    /**
     * 数据类型:ascii型
     */
    public static final int ASCII_FILE_TYPE = FTP.ASCII_FILE_TYPE;

    /**
     * 根据指定config相关信息,连接远程Ftp服务器
     * @param   ftpConfig ftp服务配置相关
     * @throws SocketException, IOException
     */
    public void connectServer(FtpConfig ftpConfig) throws SocketException, IOException {
        String server = ftpConfig.getServer();
        int port = ftpConfig.getPort();
        String username = ftpConfig.getUsername();
        String password = ftpConfig.getPassword();
        String location = ftpConfig.getLocation();
        String encode = ftpConfig.getEncode();
        connectServer(server, port, username, password, location, encode);
    }

    /**
     * 链接远程ftp服务器
     * @param server 服务器ip
     * @param port 服务器端口
     * @param user 用户名
     * @param password 密码
     * @param path 登陆后的默认路径
     * @param encode 服务器文件系统编码
     * @throws SocketException
     * @throws IOException
     */
    public void connectServer(String server, int port, String user, String password, String path, String encode)
            throws SocketException, IOException {
        ftpClient = new FTPClient();
        if (null != encode && 0 != encode.length()) {
            ftpClient.setControlEncoding(encode);
        }
        ftpClient.connect(server, port);
        ftpClient.login(user, password);
        setFileType(BINARY_FILE_TYPE);
        if (null != path && 0 != path.length()) {
            ftpClient.changeWorkingDirectory(path);
        }
    }

    /**
     * 设置文件类型
     * @param fileType 文件类型编号
     * @throws IOException
     */
    public void setFileType(int fileType) throws IOException {
        ftpClient.setFileType(fileType);
    }

    /**
     * 关闭服务器连接
     * @throws IOException
     */
    public void closeServer() throws IOException {
        if(ftpClient==null){
            ftpClient=new FTPClient();
        }
        if (ftpClient.isConnected()) {
            ftpClient.disconnect();
        }
    }

    /**
     * 改变路径
     * @param path 新路径
     * @throws IOException
     */
    public boolean changeDirectory(String path) throws IOException {
        return ftpClient.changeWorkingDirectory(path);
    }

    /**
     * 创建目录
     * @param pathName 目录名
     * @throws IOException
     */
    public boolean createDirectory(String pathName) throws IOException {
        return ftpClient.makeDirectory(pathName);
    }

    /**
     * 创建多级目录
     * @param pathName 相对路径
     * @return
     * @throws IOException
     */
    public boolean createDirectories(String pathName) throws IOException {
        
        int flag = 0;
        
        String[] paths = pathName.split("/");
        
        for(String p : paths){
            
            if(!ftpClient.changeWorkingDirectory(p)){
                
                if(ftpClient.makeDirectory(p)){
                    if(ftpClient.changeWorkingDirectory(p)){
                        flag += 1;
                    }
                }
            }else{
                flag += 1;
            }
                
        }
        
        if(flag == paths.length){
            return true;
        }
        
        return false;
    }
    
    /**
     * 删除目录
     * @param path 目录名
     * @throws IOException
     */
    public boolean removeDirectory(String path) throws IOException {
        return ftpClient.removeDirectory(path);
    }

    /**
     * 删除指定目录下全部内容(子目录和文件)
     * @param path 
     * @param isAll 确认标志位,true的时候全部删除
     * @throws IOException
     */
    public boolean removeDirectory(String path, boolean isAll) throws IOException {
        if (!isAll) {
            return removeDirectory(path);
        }

        FTPFile[] ftpFileArr = ftpClient.listFiles(path);
        if (ftpFileArr == null || ftpFileArr.length == 0) {
            return removeDirectory(path);
        }

        for (FTPFile ftpFile : ftpFileArr) {
            String name = ftpFile.getName();
            if (ftpFile.isDirectory()) {
                removeDirectory(path + "/" + name, true);
            }
            else if (ftpFile.isFile()) {
                deleteFile(path + "/" + name);
            }
            else if (ftpFile.isSymbolicLink()) {

            }
            else if (ftpFile.isUnknown()) {

            }
        }
        return ftpClient.removeDirectory(path);
    }

    /**
     * 判断指定目录是否存在
     * @param path 指定路径
     * @return 存在则返回true,否则返回false
     * @throws IOException
     */
    public boolean existDirectory(String path) throws IOException {
        boolean flag = false;
        FTPFile[] ftpFileArr = ftpClient.listFiles(path);
        for (FTPFile ftpFile : ftpFileArr) {
            if (ftpFile.isDirectory() && ftpFile.getName().equalsIgnoreCase(path)) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    /**
     * 获得指定目录下的文件列表(含子目录)
     * @param path 指定目录
     * @return 文件列表
     * @throws IOException
     */
    public List<String> getFileList(String path) throws IOException {
        FTPFile[] ftpFiles = ftpClient.listFiles(path);

        List<String> retList = new ArrayList<String>();
        if (ftpFiles == null || ftpFiles.length == 0) {
            return retList;
        }
        for (FTPFile ftpFile : ftpFiles) {
            if (ftpFile.isFile()) {
                retList.add(ftpFile.getName());
            }
        }
        return retList;
    }

    /**
     * 删除文件
     * @param pathName 文件名
     * @return 成功返回true,失败返回false
     * @throws IOException
     */
    public boolean deleteFile(String pathName) throws IOException {
        return ftpClient.deleteFile(pathName);
    }

    /**
     * 上传文件(上传同时改名)
     * @param fileName 原文件名
     * @param newName 上传后保存的文件名
     * @return 成功返回true,失败返回false
     * @throws IOException
     */
    public boolean uploadFile(String fileName, String newName) throws IOException {
        boolean flag = false;
        InputStream iStream = null;
        try {
            iStream = new FileInputStream(fileName);
            flag = ftpClient.storeFile(newName, iStream);
        }
        catch (IOException e) {
            e.printStackTrace();
            flag = false;
            throw e;
        }
        finally {
            if (iStream != null) {
                iStream.close();
            }
        }
        return flag;
    }

    /**
     * 上传文件(保持原文件名)
     * @param fileName 文件名
     * @return 成功返回true,失败返回false
     * @throws IOException
     */
    public boolean uploadFile(String fileName) throws IOException {
        return uploadFile(fileName, fileName);
    }

    /**
     * 上传文件
     * @param iStream 上传文件的InputStream
     * @param newName 上传后保存的文件名
     * @return 成功返回true,失败返回false
     * @throws IOException
     */
    public boolean uploadFile(InputStream iStream, String newName) throws IOException {
        boolean flag = false;
        try {
            // can execute [OutputStream storeFileStream(String remote)]   
            // Above method return's value is the local file stream.   
            flag = ftpClient.storeFile(newName, iStream);
        }
        catch (IOException e) {
            flag = false;
            e.printStackTrace();
            return flag;
        }
        finally {
            if (iStream != null) {
                iStream.close();
            }
        }
        return flag;
    }

    /**
     * 下载文件
     * @param remoteFileName 远程文件名
     * @param localFileName 下载后,本地保存的文件名
     * @return 成功返回true,失败返回false
     * @throws IOException
     */
    public boolean download(String remoteFileName, String localFileName) throws IOException {
        boolean flag = false;
        File outfile = new File(localFileName);
        OutputStream oStream = null;
        try {
            oStream = new FileOutputStream(outfile);
            flag = ftpClient.retrieveFile(remoteFileName, oStream);
        }
        catch (IOException e) {
            flag = false;
            return flag;
        }
        finally {
            oStream.close();
        }
        return flag;
    }

    /**
     * 取得远程文件的Stream
     * @param sourceFileName
     * @return 取得远程文件的Stream
     * @throws IOException
     */
    public InputStream downFile(String sourceFileName) throws IOException {
        return ftpClient.retrieveFileStream(sourceFileName);
    }

    /**
     * 下载文件,将远程FTP文件,写入HttpServletResponse
     * @param remoteFileName 远程文件名
     * @param response servlet的响应
     * @throws IOException
     */
    public void download(String remoteFileName, HttpServletResponse response) throws IOException {

        if (ftpClient == null) {
            ftpClient = new FTPClient();
        }
        
        if (!ftpClient.isConnected()) {
            this.connectServer(new FtpConfig());
        }

        OutputStream os = null;
        try {
            os = response.getOutputStream();
            ftpClient.retrieveFile(remoteFileName, os);

        }
        catch (IOException e) {
            throw new RuntimeException("远程文件" + remoteFileName + "读入失败" + e.getMessage());
        }
        finally {
            if (os != null) {
                os.close();
            }
        }
        if (ftpClient != null) {
            if (ftpClient.isConnected()) {
                ftpClient.disconnect();
            }
        }
    }
    
    /**
     * 下载文件,将远程FTP文件,写入HttpServletResponse
     * @param remoteFileName 远程文件名
     * @param response servlet的响应
     * @throws IOException
     */
    public InputStream downloadImage(String remoteFileName) throws IOException {

        if (ftpClient == null) {
            ftpClient = new FTPClient();
        }
        
        if (!ftpClient.isConnected()) {
            this.connectServer(new FtpConfig());
        }
        InputStream ins=null;
        try {
            ins=ftpClient.retrieveFileStream(remoteFileName);
            if (ftpClient != null) {
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            }
        }
        catch (IOException e) {
            throw new RuntimeException("远程文件" + remoteFileName + "读入失败" + e.getMessage());
        }finally{
            
        }
        return ins;
    }
    
    /**
     * 判断指定文件是否存在
     * @param file 指定文件
     * @return 存在则返回true,否则返回false
     * @throws IOException
     */
    public boolean existFile(String file) throws IOException {
        boolean flag = false;
        FTPFile[] ftpFileArr = ftpClient.listFiles(file);
        if (null != ftpFileArr && ftpFileArr.length > 0) {
           flag = true;
        }
        
        return flag;
    }

    public double fileSize(String file) throws IOException{
        FTPFile[] ftpFileArr = ftpClient.listFiles(file);
        double  fileSize = 0.0;
        if (null != ftpFileArr && ftpFileArr.length > 0) {
            fileSize = (double) ftpFileArr[0].getSize();
        }
        return fileSize;
    }
    
}

SFTP

package cn.greatlife.wechat.util;

import cn.greatlife.wechat.common.config.FtpConfig;
import com.github.pagehelper.util.StringUtil;
import com.jcraft.jsch.*;
import com.jcraft.jsch.ChannelSftp.LsEntry;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

/**
 * Sftp调用工具类
 * 
 * @date 2018-11-20
 * @author XXXX
 * @version 1.0
 * 
 */
public class SftpUtil {
    /**
     * 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服务器
     * 
     * @param ftpConfig
     *            ftp服务配置信息类
     */
    public void connectServer(FtpConfig ftpConfig) {
        String server = ftpConfig.getServer();
        int port = ftpConfig.getPort();
        String username = ftpConfig.getUsername();
        String password = ftpConfig.getPassword();
        String location = "/";
        if (null != ftpConfig.getLocation() && !"".equals(ftpConfig.getLocation())) {
            location = ftpConfig.getLocation();
        }
        String encode = ftpConfig.getEncode();
        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(StringUtil.isNotEmpty(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());
        }
    }

    /**
     * 内部方法,取得当前操作目录下的全部文件列表
     */
    private void getCurrentFileList() {
        try {
            Vector v = channelSftp.ls(currentPath);
            this.currentFiles = v;
        }
        catch (SftpException e) {
            e.printStackTrace();
        }
    }

    /**
     * 内部方法,获得操作路径
     * 
     * @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 remoteFilePath
     * @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;
        }
    }

    /**
     * 上传文件
     * 
     * @return -1 文件不存在 -2 文件内容为空 >0 成功上传,返回文件的大小
     * @param remoteFilePath
     *            远程文件名  remoteFilePath = 远程目录+文件名
     * @param localFilepath
     *            本地文件名
     */
    @SuppressWarnings("finally")
    public long upload(String remoteFilePath, 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();
                // 从本地上传到服务器
                channelSftp.put(is, remoteFilePath);
            }
            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;
    }

    /**
     * 上传文件
     * 
     * @return -1 文件不存在 -2 文件内容为空 >0 成功上传,返回文件的大小
     * @param remoteFilePath
     *            远程文件名 这个remoteFilePath = 远程目录+文件名
     * @param localFilepath
     *            本地文件名
     */
    @SuppressWarnings("finally")
    public long upload(String remoteFilePath, InputStream is) {
        if (channelSftp == null || !channelSftp.isConnected()) {
            throw new RuntimeException("上传文件时发生异常,channelSftp连接未创建");
        }
        long result = -1;
        try {
            // 从本地上传到服务器
            channelSftp.put(is, remoteFilePath);
        }
        catch (SftpException e) {
            throw new RuntimeException(e.getMessage() + ": 上传文件时发生错误!");
        }
        finally {
            closeInputStream(is);
            
        }
        return result;
    }

    
    /**
     * 上传文件
     * @param filename 文面名
     * @return 操作结果
     */
    public long upload(String filename) {
        String newname = "";
        if (filename.lastIndexOf("/") > -1) {
            newname = filename.substring(filename.lastIndexOf("/") + 1, filename.length());
        }
        else {
            newname = filename;
        }
        return upload(newname, filename);
    }

  
    /**
     * 关闭连接
     */
    public void closeConnection() {
        if (channelSftp != null) {
            if (channelSftp.isConnected()) {
                channelSftp.disconnect();
                session.disconnect();
            }
        }
    }

    /**
     * 下载文件,并写入HttpServletResponse(浏览器方式)
     * @param remoteFilePath 远程文件路径
     * @param response HttpServletResponse
     * @param fileName 通过浏览器,下载时看到的文件名
     * @return 操作结果,成功返回true,失败返回false
     */
    public boolean downloadFile(String remoteFilePath, HttpServletResponse response, String fileName) {
        if (dirValidation(remoteFilePath)) {
            if (!existFile(remoteFilePath)) {
                throw new RuntimeException("下载文件" + remoteFilePath + "时发生异常,远程文件并不存在");
            }
            OutputStream os = null;
            //String fileName = remoteFilePath.substring(remoteFilePath.lastIndexOf(File.separator) + 1);
            try {
                response.setHeader("Content-disposition", "attachment;filename="
                        + new String(fileName.getBytes("GBK"), "ISO8859-1"));
                os = response.getOutputStream();
                // 从服务器下载到本地
                channelSftp.get(remoteFilePath, os);
                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
     * @param response
     * @param fileName
     * @return
     */
    public boolean writeFile(String remoteFilePath,
			HttpServletResponse response, String fileName) {
		if (dirValidation(remoteFilePath)) {
			if (!existFile(remoteFilePath)) {
				throw new RuntimeException("下载文件" + remoteFilePath
						+ "时发生异常,远程文件并不存在");
			}
			try {
				// 从服务器下载到本地
				InputStream in = channelSftp.get(remoteFilePath);
				if (in != null) {
					byte[] b = new byte[1024];
					int len;
					while ((len = in.read(b)) != -1) {
						response.getOutputStream().write(b);
					}
					in.close();
				}
				return true;
			} catch (IOException e) {
				throw new RuntimeException("读取文件:" + remoteFilePath
						+ "时发生文件读写错误:" + e.getMessage());
			} catch (SftpException e) {
				throw new RuntimeException("读取文件:" + remoteFilePath
						+ "时发生Sftp错误:" + e.getMessage());
			}
		} else {
			return false;
		}
	}

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值