JAva操作sftpファイル(コード操作サーバファイル)

10909 ワード

必要に応じて、ファイルのアップロードやダウンロードなど、サードパーティのサーバをファイル操作します.の以下は具体的な実装コードで、同じニーズの戦友を助けることができることを望んで、疑問があれば微信で交流することができます:【shedexinjing】
package com.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;



public class SFTPUtil {
	private static final Log log = LogFactory.getLog(SFTPUtil.class);
	/** sftp       
	 * @param path            
	 * @param fileName      
	 * @return             #@#        ,          
	 * @throws JSchException  
	 * @throws Exception
	 */
	public static String downLoadFileTxt(String SFTPType,String path,String fileName) throws JSchException,  Exception{
		log.info("down_load_file:"+path+"/"+fileName);
		Session session = null;
		ChannelSftp sftpChannel = null;
		InputStream is = null;
		BufferedReader buf = null;
		StringBuffer content = new StringBuffer();
		try {
			session = getSession(SFTPType);
			
			Channel channel=session.openChannel("sftp"); //   SFTP   
			channel.connect(); //   SFTP     
		    sftpChannel=(ChannelSftp)channel;  
		    sftpChannel.cd(path);
		
			is = sftpChannel.get(fileName);
			if(is==null){
				throw new CashException("     ");
			}else{
				buf = new BufferedReader(new InputStreamReader(is,"UTF-8"));
				String tcontent = null;
				
				while((tcontent = buf.readLine())!=null){
					if(StringUtils.isNotEmpty(tcontent)){
						content.append(CashServiceConstant.DOWN_TEXT_LINE_SPLIT).append(tcontent);
					}
				}
			}
		} catch (Exception e) {
			throw e;
		}finally{
			if(is!=null)is.close();
			if(buf!=null)buf.close();
			if(sftpChannel!=null)sftpChannel.disconnect();
			if(session!=null) session.disconnect();
		}
		//      
		if(content.toString().startsWith(CashServiceConstant.DOWN_TEXT_LINE_SPLIT)){
			return content.toString().replaceFirst(CashServiceConstant.DOWN_TEXT_LINE_SPLIT, "");
		}else{
			return content.toString();
		}
	}
	
	/**
	 * @param SFTPType
	 * @param sFile            
	 * @param dFile            
	 * @return
	 * @throws JSchException
	 * @throws Exception
	 */
	public static boolean rename(String SFTPType,String sFile,String dFile) throws JSchException,  Exception{
		Session session = null;
		ChannelSftp sftpChannel = null;
		try {
			session = getSession(SFTPType);
			Channel channel=session.openChannel("sftp"); //   SFTP   
			channel.connect(); //   SFTP     
		    sftpChannel=(ChannelSftp)channel;  
		    sftpChannel.rename(sFile, dFile);
		    return true;
		} catch (Exception e) {
			log.error("",e);
			return false;
		}finally{
			if(sftpChannel!=null)sftpChannel.disconnect();
			if(session!=null) session.disconnect();
		}
	}
	/**      
	 * @param SFTPType        sftp     DJ_SFTP_USER      SFTPType=DJ
	 * @param paths       /      
	 * @return
	 * @throws JSchException
	 * @throws Exception
	 */
	public static boolean getMkdirs(String SFTPType,List paths) throws JSchException,  Exception{
		Session session = null;
		ChannelSftp sftpChannel = null;
		try {
			session = getSession(SFTPType);
			Channel channel=session.openChannel("sftp"); //   SFTP   
			channel.connect(); //   SFTP     
		    sftpChannel=(ChannelSftp)channel;  
		    int size = paths.size();
		    for(int i=0;i getLs(String SFTPType,String path) throws JSchException,  Exception{
		Session session = null;
		ChannelSftp sftpChannel = null;
		List fs = new ArrayList();
		try {
			session = getSession(SFTPType);
			Channel channel=session.openChannel("sftp"); //   SFTP   
			channel.connect(); //   SFTP     
		    sftpChannel=(ChannelSftp)channel;  
		    //sftpChannel.cd(path);
		    log.debug("ls_pwd="+sftpChannel.pwd());
		    Vector fileList = sftpChannel.ls(path);
		    fs= parseList(fileList);
		} catch (Exception e) {
			throw e;
		}finally{
			if(sftpChannel!=null)sftpChannel.disconnect();
			if(session!=null) session.disconnect();
		}
		 return fs;
	}
	/**      
	 * @param SFTPType
	 * @return
	 * @throws JSchException
	 * @throws Exception
	 */
	public static String getPwd(String SFTPType) throws JSchException,  Exception{
		Session session = null;
		ChannelSftp sftpChannel = null;
		try {
			session = getSession(SFTPType);
			Channel channel=session.openChannel("sftp"); //   SFTP   
			channel.connect(); //   SFTP     
		    sftpChannel=(ChannelSftp)channel;  
		    String pwd = sftpChannel.pwd();
		    log.debug("pwd="+pwd);
		    return pwd;
		} catch (Exception e) {
			throw e;
		}finally{
			if(sftpChannel!=null)sftpChannel.disconnect();
			if(session!=null) session.disconnect();
		}
	}
	
	/**  ftp
	 * @param SFTPType        sftp     DJ_SFTP_USER      SFTPType=DJ
	 * @return
	 */
	public static Session getSession(String SFTPType){
		JSch jsch=new JSch(); 
		Session session = null;
		try {
			// properties            ,    
			String user = Properties.getValue(SFTPType+"_SFTP_USER");
			String passwd = Properties.getValue(SFTPType+"_SFTP_PASSWD");
			String host = Properties.getValue(SFTPType+"_SFTP_HOST");
			int port = Properties.getInt(SFTPType+"_SFTP_PORT");
			log.debug("user>>"+user);
			log.debug("passwd>>"+passwd);
			log.debug("host>>"+host);
			log.debug("host>>"+host);
			session=jsch.getSession(user, host, port);  
			session.setPassword(passwd);
			Properties config = new java.util.Properties();
			config.put("StrictHostKeyChecking", "no");
			session.setConfig(config);
			Integer timeout = CashProperties.getInt(SFTPType+"_SFTP_TIMEOUT");
			session.setTimeout(timeout==null?6000:timeout); //   timeout  
			session.connect();
			return session;
		} catch (JSchException e) {
			e.printStackTrace();
			if(session!=null && session.isConnected()){
				session.disconnect();
			}
			return null;
		} 
	}
	/**
	 *           
	 * @param SFTPType       DJ
	 * @param directory       
	 * @param desdir      
	 */
	public static void deleteAll(String SFTPType,String directory,String desdir) {
		Session session = null;
		ChannelSftp sftpChannel = null;
	    try {
	    	session = getSession(SFTPType);
	    	Channel channel=session.openChannel("sftp"); //   SFTP   
	    	channel.connect();
	    	sftpChannel=(ChannelSftp)channel;
	    	//            ,                  
	    	Vector fileList = null;
	    	try {
				fileList = sftpChannel.ls(directory+"/"+desdir);
			} catch (Exception e) {
				log.debug(directory+"/"+desdir+",      ");
				return;
			}
		    List list= parseList(fileList);
		    sftpChannel.cd(directory+"/"+desdir);
		    for (int i = 0; i < list.size(); i++) {
		    	
		    	sftpChannel.rm(list.get(i));
		    }
		    sftpChannel.cd("../");
	    	sftpChannel.rmdir(desdir);
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }finally{
			if(sftpChannel!=null)sftpChannel.disconnect();
			if(session!=null) session.disconnect();
		}
    }
	/**
	 *     
	 * @param SFTPType        DJ
	 * @param directory ftp     
	 * @param downloadFile        
	 * @param saveDirectory        
	 * @throws Exception
	 */
	public static void download(String SFTPType,String directory, String downloadFile, String saveDirectory)
		    throws Exception
		  {
		Session session = null;
		ChannelSftp sftpChannel = null;
		FileOutputStream fileOutputStream = null;
		try {
			String saveFile = saveDirectory + "//" + downloadFile;
			session = getSession(SFTPType);
	    	Channel channel=session.openChannel("sftp"); //   SFTP   
	    	channel.connect();
	    	sftpChannel=(ChannelSftp)channel;
	    	sftpChannel.cd(directory);
		    File file = new File(saveFile);
		    fileOutputStream = new FileOutputStream(file);
		    sftpChannel.get(downloadFile, fileOutputStream);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(fileOutputStream!=null){fileOutputStream.close();}
			if(sftpChannel!=null)sftpChannel.disconnect();
			if(session!=null) session.disconnect();
		}
		   
	 }
	
	public static List parseList(Vector fileList){
		List list= new ArrayList();
		Iterator it = fileList.iterator();
	    while (it.hasNext())
	    {
	      String fileName = ((ChannelSftp.LsEntry)it.next()).getFilename();
	      if ((".".equals(fileName)) || ("..".equals(fileName))) {
	        continue;
	      }
	      list.add(fileName);
	    }
	    return list;
	}
	/**
	 *     ,  InputStream
	 */
	public static byte[] downLoadFileIo(String SFTPType,String path,String fileName) throws JSchException,  Exception{
		log.info("    ,down_load_file:"+path+"/"+fileName);
		Session session = null;
		ChannelSftp sftpChannel = null;
		InputStream is = null;
		byte[] bs = null;
		try {
			session = getSession(SFTPType);
			Channel channel=session.openChannel("sftp"); //   SFTP   
			channel.connect(); //   SFTP     
		    sftpChannel=(ChannelSftp)channel;  
		    sftpChannel.cd(path);
			is = sftpChannel.get(fileName);
			bs = readInputStream(is);
		} catch (Exception e) {
			throw e;
		}finally{
			if(is!=null)is.close();
			if(sftpChannel!=null)sftpChannel.disconnect();
			if(session!=null) session.disconnect();
		}
		return bs;
	}
	/**
	 *            
	 * 
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	private static  byte[] readInputStream(InputStream inputStream) throws IOException {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while ((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		return bos.toByteArray();
	}
}