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