java创建SFtp连接工具类及文件处理


SftpUtil  (其一)

package com.cdc.cloud.appContentTask.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

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;

/**
 * 类名:SFtp
 * 功能:java创建SFtp连接工具类(原FtpUtil对于sftp协义无法连接,故使用这种方式,旧业务仍在使用)
 * @author 
 * @date 
 *
 */
public class SFtp {
	
	private String host;						//主机名
	
	private int port;							//端口
	
	private String userName;					//ftp用户名
	
	private String passWord;					//ftp密码
	
	private Session sshSession;					//ssh会话
	
	private Channel channel;					//通道
	
	private ChannelSftp csftp;					//强转后的ftp通道
	
	public SFtp(String host,int port,String userName,String passWord){
		this.host = host;
		this.port = port;
		this.userName = userName;
		this.passWord = passWord;
	}
	
	/**
	 * 方法名:connect<br>
	 * 作用:连接fth<br>
	 * @author lhong<br>
	 * @date 2016-05-31<br>
	 */
	public boolean connect(){
		JSch jsch = new JSch();
		try {
			sshSession = jsch.getSession(userName, host, port);
			sshSession.setPassword(passWord);
			Properties sshConfig = new Properties();
			sshConfig.put("StrictHostKeyChecking", "no");
			sshSession.setConfig(sshConfig);
			
			sshSession.connect();
			
			channel = sshSession.openChannel("sftp");
			channel.connect();
			
			csftp = (ChannelSftp) channel;
		} catch (JSchException e) {
			e.printStackTrace();
			disconnect();
			return false;
		}
		return true;
	}
	
	/**
	 * 方法名:disconnect<br>
	 * 作用:断开ftp连接<br>
	 * @author lhong<br>
	 * @date 2016-05-31<br>
	 */
	public void disconnect(){
		if(csftp != null && csftp.isConnected())
			csftp.disconnect();
		if(channel != null && channel.isConnected())
			channel.disconnect();
		if(sshSession != null && sshSession.isConnected())
			sshSession.disconnect();
	}
	
	/**
	 * 方法名:readFile<br>
	 * 作用:获得读取文件的输入流<br>
	 * @author lhong<br>
	 * @date 2016-05-31<br>
	 */
	public InputStream readFile(String filePath){
		try {
			return csftp.get(filePath);
		} catch (SftpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			disconnect();
			return null;
		}
	}
	/**
	 * 获取ftp指定路径下所有文件的 文件路径
	 */
	public List<String> listFilesUrl(String dirPath){
		List<String> list = new ArrayList<String>();
		Vector<?> files = null;
		try {
			files = csftp.ls(dirPath);
			Iterator it = files.iterator();
			while(it.hasNext()){
				LsEntry entry = (LsEntry)it.next();
				String fileName = entry.getFilename();
				if(fileName.trim().equals(".")||fileName.equals("src/main")||fileName.equals("..")) {
					it.remove();
					continue;
				}
//				System.out.println(fileName);
				list.add(dirPath+"/"+fileName);
			}
		} catch (SftpException e) {
			e.printStackTrace();
			disconnect();
		} catch (Exception e1){
			e1.printStackTrace();
			disconnect();
		}
		return list;
}
	
	/**
	 * 方法名:listFiles<br>
	 * 作用:取得目录下的文件或目录列表<br>
	 * @param dirPath : 目录路径
	 * @author lhong<br>
	 * @date 2016-05-31<br>
	 */
	public Vector<?> listFiles(String dirPath){
			Vector<?> files = null;
			try {
				files = csftp.ls(dirPath);
				Iterator it = files.iterator();
				while(it.hasNext()){
					LsEntry entry = (LsEntry)it.next();
					String fileName = entry.getFilename();
					if(fileName.equals(".")||fileName.equals("src/main"))
						it.remove();
				}
			} catch (SftpException e) {
				e.printStackTrace();
				disconnect();
			} catch (Exception e1){
				e1.printStackTrace();
				disconnect();
			}
			return files;
	}
	
	/**
	 * 方法名:rename<br>
	 * 作用:重命名文件<br>
	 * @param src : 源(修改前)
	 * @param dst : 目标(修改后)
	 * @author lhong<br>
	 * @date 2016-05-31<br>
	 */
	public boolean rename(String src,String dst){
		try {
			//这里要对目标文件的目录做一个校验,如果不存在要创建对应目录
			String dirPath = dst.substring(0,dst.lastIndexOf("/"));
			mkdirs(dirPath);
			csftp.rename(src, dst);
			return true;
		} catch (SftpException e) {
			e.printStackTrace();
			disconnect();
			return false;
		}
	}
	
	/**
	 * 方法名:delete<br>
	 * 作用:删除文件<br>
	 * @param path : 删除文件或目录的路径
	 * @author lhong<br>
	 * @date 2016-06-01<br>
	 */
	public boolean delete(String path){
		try {
			if(path.indexOf(".")>-1)
				csftp.rm(path);
			else
				csftp.rmdir(path);
		} catch (SftpException e) {
			disconnect();
			e.printStackTrace();
		}
		return true;
	}
	
	/**
	 * 方法名:download<br>
	 * 作用:上传文件或目录到指定目录<br>
	 * @param dstDirPath : 本地存放目录的地址
	 * @param srcPath : 服务器上的文件或目录的地址
	 * @author lhong<br>
	 * @date 2016-05-31<br>
	 */
	public boolean download(String dstDirPath,String srcPath){
		
		if(null==dstDirPath || "".equals(dstDirPath)){
			return false;
		}
		if(null==srcPath || "".equals(srcPath)){
			return false;
		}
		
		File dst = new File(dstDirPath);
		
		if(!dst.exists()){
			dst.mkdirs();
		}
		
		FileOutputStream fos = null;
		
		try {
			if(srcPath.indexOf(".")>-1){
				//当源为文件时
				String fileName = srcPath.substring(srcPath.lastIndexOf("/"));
				String dstFileName = dstDirPath + "/" + fileName;
				fos = new FileOutputStream(new File(dstFileName));
				System.out.println(csftp);
				csftp.get(srcPath, fos);
			}else{
				//当源为目录时
				Vector<?> files = listFiles(srcPath);
				for (Object file : files) {
					LsEntry entry = (LsEntry)file;
					String fileName = entry.getFilename();
					
					String childSrcDirPath = srcPath+"/"+fileName;
					if(fileName.indexOf(".")==-1){
						dstDirPath+="/"+fileName;
					}
					if(!fileName.equals("..")) {
						download(dstDirPath,childSrcDirPath);
					}
				}
			}
		} catch (FileNotFoundException e) {
			System.out.println("下载的源目录或文件,不存在......下载失败!!!");
			e.printStackTrace();
			disconnect();
			return false;
		} catch (SftpException e) {
			e.printStackTrace();
			disconnect();
			return false;
		} finally {
			//回收流,防上泄露
			if(null!=fos)
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return true;
	}
	
	
	/**
	 * 方法名:upload<br>
	 * 作用:上传文件或目录到指定目录<br>
	 * @param dstDirPath : 服务器上的目录地址
	 * @param srcPath : 本地上传文件或目录的路径
	 * @author lhong<br>
	 * @date 2016-05-31<br>
	 */
	public boolean upload(String dstDirPath,String srcPath){
		
		if(null==dstDirPath || "".equals(dstDirPath)){
			return false;
		}
		if(null==srcPath || "".equals(srcPath)){
			return false;
		}
		
		File src = new File(srcPath);
		FileInputStream fis = null;
		try {
			//检索并创建目录树
			mkdirs(dstDirPath);
			
			if(src.isFile()){
				//如果上传的是文件
				fis = new FileInputStream(src);
				csftp.put(fis, src.getName());
			}else{
				//如果上传的是目录
				String dirPath = dstDirPath+"/"+src.getName();
				//1.创建对应的目录,并进入
				mkdirs(dirPath);
				csftp.cd(dirPath);
				File[] files = src.listFiles();
				for (int i = 0; i < files.length; i++) {
					File file = files[i];
					upload(dirPath,file.getPath());
				}
			}
		} catch (FileNotFoundException e) {
			System.out.println("上传的源目录或文件,不存在......上传失败!!!");
			e.printStackTrace();
			disconnect();
			return false;
		} catch (SftpException e) {
			e.printStackTrace();
			disconnect();
			return false;
		} finally {
			//回收流,防上泄露
			if(null!=fis)
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return true;
	}
	
	/**
	 * 方法名:mkdirs<br>
	 * 作用:创建文件夹,如果是多层文件夹,则依次创建<br>
	 * @param path : 文件夹地址
	 * @author lhong<br>
	 * @date 2016-05-31<br>
	 */
	public void mkdirs(String path){
		//先文件目录格式标准化,"/"为分隔符
		path = path.replaceAll("/+|\\\\+", "/");
		//解析目录并创建
		String[] dirs = path.split("(?!^/)+/");
		
		for (int i = 0; i < dirs.length; i++) {
			try {
				csftp.cd(dirs[i]);
			} catch (SftpException e) {
				try {
					csftp.mkdir(dirs[i]);
					csftp.cd(dirs[i]);
				} catch (SftpException e1) {
					e1.printStackTrace();
					disconnect();
				}
			}
		}
	}
	
	
	
//	public static void main(String[] args) {
//
//		SFtp sftp = new SFtp("192.168.16.100",22,"root","ffcsnss");
//		if(sftp.connect())
////			sftp.upload("/home/GZ3A", "D:\\1.txt");
//			sftp.download("static/2/", "/opt/nss/upload/policy/acf1b7ef-62ee-4343-8739-7464f5f6defb.pdf");
//			//sftp.rename("/home/GZ3A/Origin/123/Trojan_Controlled_20151120133020_update.xls", "/home/GZ3A/Origin/223/Trojan_Controlled_20151120133020_update.xls");
//			//sftp.delete("/home/GZ3A/Origin/223");
//			//System.out.println(sftp.listFiles("/home/GZ3A/Origin/123"));
//
//		sftp.disconnect();
//	}
	

}

  SftpUtil  (其二)

package com.apexsoft.utils;

import com.jcraft.jsch.*;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import org.apache.log4j.Logger;
import java.io.*;
import java.util.*;

/**
 * sftp工具类
 *
 * @author 
 * @version 1.0
 * @date 
 * @time 
 */
public class SftpUtils {
    private static Logger log = Logger.getLogger(SftpUtils.class);

    private String host;//服务器连接ip
    private String username;//用户名
    private String password;//密码
    private int port;//端口号
    private ChannelSftp sftp = null;
    private Session sshSession = null;

    public SftpUtils() {
    }

    public SftpUtils(String host, int port, String username, String password) {
        this.host = host;
        this.username = username;
        this.password = password;
        this.port = port;
    }

    public SftpUtils(String host, String username, String password) {
        this.host = host;
        this.username = username;
        this.password = password;
    }

    /**
     * 通过SFTP连接服务器
     */
    public void ftpLogin() {
        try {
            JSch jsch = new JSch();
            jsch.getSession(username, host, port);
            sshSession = jsch.getSession(username, host, port);
            if (log.isInfoEnabled()) {
                log.info("Session created.");
            }
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            if (log.isInfoEnabled()) {
                log.info("Session connected.");
            }
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            if (log.isInfoEnabled()) {
                log.info("Opening Channel.");
            }
            sftp = (ChannelSftp) channel;
            if (log.isInfoEnabled()) {
                log.info("Connected to " + host + ".");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接
     */
    public void ftpLogOut() {
        if (this.sftp != null) {
            if (this.sftp.isConnected()) {
                this.sftp.disconnect();
                if (log.isInfoEnabled()) {
                    log.info("sftp is closed already");
                }
            }
        }
        if (this.sshSession != null) {
            if (this.sshSession.isConnected()) {
                this.sshSession.disconnect();
                if (log.isInfoEnabled()) {
                    log.info("sshSession is closed already");
                }
            }
        }
    }

    /**
     * 批量下载文件
     *
     * @param remotePath:远程下载目录
     * @param localPath:本地保存目录
     * @return
     */
    public List<String> downLoadDirectory(String remotePath, String localPath) {
        List<String> filenames = new ArrayList<String>();
        try {
            Vector v = listFiles(remotePath);
             sftp.cd(remotePath);
            if (v.size() > 0) {
                //System.out.println("本次处理文件个数不为零,开始下载...fileSize=" + v.size());
                Iterator it = v.iterator();
                while (it.hasNext()) {
                    LsEntry entry = (LsEntry) it.next();
                    String filename = entry.getFilename();
                    SftpATTRS attrs = entry.getAttrs();
                    if (!attrs.isDir()) {
                        boolean flag = false;
                        String localFileName = localPath + filename;
                        flag = downloadFile(remotePath, filename, localPath, filename);
                        if (flag) {
                            filenames.add(localFileName);
                        }
                    }
                }
            }
            if (log.isInfoEnabled()) {
                log.info("download file is success:remotePath=" + remotePath
                        + "and localPath=" + localPath + ",file size is"
                        + v.size());
            }
        } catch (SftpException e) {
            e.printStackTrace();
        } finally {
            // this.disconnect();
        }
        return filenames;
    }

    /**
     * 下载单个文件
     *
     * @param remotePath:远程下载目录(以路径符号结束)
     * @param remoteFileName:下载文件名
     * @param localPath:本地保存目录(以路径符号结束)
     * @param localFileName:保存文件名
     * @return
     */
    public boolean downloadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {
        FileOutputStream fieloutput = null;
        try {
            sftp.cd(remotePath);
            File file = new File(localPath+"/" + localFileName);
            mkdirs(localPath +"/" + localFileName);
            fieloutput = new FileOutputStream(file);
            sftp.get(remotePath +"/"+ remoteFileName, fieloutput);
            if (log.isInfoEnabled()) {
                log.info("===DownloadFile:" + remoteFileName + " success from sftp.");
            }
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        } catch (SftpException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        } finally {
            if (null != fieloutput) {
                try {
                    fieloutput.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    log.error(e.getMessage());
                }
            }
        }
        return false;
    }

    /**
     * 上传单个文件
     *
     * @param remotePath:远程保存目录
     * @param remoteFileName:保存文件名
     * @param localPath:本地上传目录
     * @param localFileName:上传的文件名
     * @return
     */
    public boolean uploadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {
        FileInputStream in = null;
        try {
            createDir(remotePath);
            File file = new File(localPath + localFileName);
            in = new FileInputStream(file);
            sftp.put(in, remoteFileName);
            if (log.isInfoEnabled()) {
                log.info("===uploadFile:" + localFileName + " success from sftp.");
            }
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.error("中登文件申报:"+e.getMessage());
        } catch (SftpException e) {
            e.printStackTrace();
            log.error("中登文件申报:"+e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    log.error("中登文件申报:"+e.getMessage());
                }
            }
        }
        return false;
    }

    /**
     * 批量上传文件
     *
     * @param remotePath:远程保存目录
     * @param localPath:本地上传目录(以路径符号结束) //* @param del:上传后是否删除本地文件
     * @return
     */
    public boolean uploadDirectory(String remotePath, String localPath) {
        boolean flag=true;
        try {
            //ftpLogin();
            File file = new File(localPath);
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()) {
                     flag = uploadFile(remotePath, files[i].getName(), localPath + "/", files[i].getName());
                    if (flag != true) {
                        break;
                    }
                }
            }
            if (log.isInfoEnabled()) {
                log.info("upload file is success:remotePath=" + remotePath
                        + "and localPath=" + localPath + ",file size is "
                        + files.length);
            }
            return flag;
        } catch (Exception e) {
            e.printStackTrace();
        } /*finally {
            this.ftpLogOut();
        }*/
        return flag;
    }

    /**
     * 删除本地文件
     *
     * @param filePath
     * @return
     */
    public boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return false;
        }

        if (!file.isFile()) {
            return false;
        }
        boolean rs = file.delete();
        if (rs && log.isInfoEnabled()) {
            log.info("delete file success from local.");
        }
        return rs;
    }

    /**
     * 创建目录
     *
     * @param createpath
     * @return
     */
    public boolean createDir(String createpath) {
        try {
            if (exists(createpath)) {
                this.sftp.cd(createpath);
                return true;
            }
            String pathArry[] = createpath.split("/");
            StringBuffer filePath = new StringBuffer("/");
            for (String path : pathArry) {
                if (path.equals("")) {
                    continue;
                }
                filePath.append(path + "/");
                if (exists(filePath.toString())) {
                    sftp.cd(filePath.toString());
                } else {
                    // 建立目录
                    sftp.mkdir(filePath.toString());
                    // 进入并设置为当前目录
                    sftp.cd(filePath.toString());
                }

            }
            this.sftp.cd(createpath);
            return true;
        } catch (SftpException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断目录是否存在
     *
     * @param directory
     * @return
     */
    public boolean exists(String directory) {
        boolean isDirExistFlag = false;
        try {
            SftpATTRS sftpATTRS = sftp.lstat(directory);
            isDirExistFlag = true;
            return sftpATTRS.isDir();
        } catch (Exception e) {
            if (e.getMessage().toLowerCase().equals("no such file")) {
                isDirExistFlag = false;
            }
        }
        return isDirExistFlag;
    }

    /**
     * 删除stfp文件
     *
     * @param directory:要删除文件所在目录
     * @param deleteFile:要删除的文件
     */
    public void deleteSFTP(String directory, String deleteFile) {
        try {
            // sftp.cd(directory);
            sftp.rm(directory + deleteFile);
            if (log.isInfoEnabled()) {
                log.info("delete file success from sftp.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 如果目录不存在就创建目录
     *
     * @param path
     */
    public void mkdirs(String path) {
        File f = new File(path);

        String fs = f.getParent();

        f = new File(fs);

        if (!f.exists()) {
            f.mkdirs();
        }
    }
    public boolean existsIndexFile(String pathName,String ext){
        Vector vector = new Vector();
        boolean flag=true;
        //FTPFile[] files={};
        if(pathName.startsWith("/")&&pathName.endsWith("/")){
           // String directory = pathName;
            //更换目录到当前目录
            try {
                sftp.cd(pathName);
                 vector = listFiles(pathName);
            } catch (SftpException e) {
                e.printStackTrace();
            }
            Iterator it = vector.iterator();
            while (it.hasNext()) {
                LsEntry entry = (LsEntry) it.next();
                String filename = entry.getFilename();
                if(filename.equals(ext)){
                    return flag;
                }
            }
        }
        flag=false;
        return flag;
    }

    /**
     * 列出目录下的文件
     *
     * @param directory:要列出的目录
     * @return
     * @throws SftpException
     */
    public Vector listFiles(String directory) throws SftpException {
        return sftp.ls(directory);
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public ChannelSftp getSftp() {
        return sftp;
    }

    public void setSftp(ChannelSftp sftp) {
        this.sftp = sftp;
    }

    /**
     * 测试
     *  khsftp.mintrust.dev
     *  crmuser/Crm_1234,tauser/Ta_12345
     */
    public static void main(String[] args) {
        SftpUtils sftp = null;
        // 本地存放地址
        String localPath = "C:\\testSftp\\";
        // Sftp下载路径
        String sftpPath = "/opt/input";
        List<String> filePathList = new ArrayList<String>();
        try {
            sftp = new SftpUtils("192.168.3.80", 22,"root", "apexxt!@#380");
            sftp.ftpLogin();
            // 下载
            sftp.downLoadDirectory(sftpPath, localPath);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sftp.ftpLogOut();
        }
    }
}

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM