標籤:host 上傳下載 shc 檔案服務 final str 配置 throw nbsp
檔案伺服器採用FreeSSHd,檔案伺服器配置就不細說了。
直接上代碼,該代碼可以直接使用。
import com.jcraft.jsch.*;import java.io.InputStream;import java.util.Properties;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * @author fc * @version V1.0 * @Title SFTPConnect * @Package com.jsch * @Descript :TODO() * @date : 2018/8/30 下午3:50 */public class SftpConnect { private String user; private String password; private String host; private int port; private ChannelSftp channelSftp; private Session session; private Logger logger = LoggerFactory.getLogger(SftpConnect.class); private final String NO_SUCH_FILE = "No such file"; public SftpConnect(String user, String password, String host, int port) { this.user = user; this.password = password; this.host = host; this.port = port; } private ChannelSftp connect(){ JSch jSch=new JSch(); try { session=jSch.getSession(user,host,port); Properties sshConfig = new Properties(); sshConfig.put("StrictHostKeyChecking", "no"); session.setPassword(password); session.setConfig(sshConfig); session.connect(); channelSftp= (ChannelSftp) session.openChannel("sftp"); channelSftp.connect(); } catch (JSchException e) { return null; } return channelSftp; } /** * 中斷連線 */ private void disconnect() { channelSftp.disconnect(); session.disconnect(); } public boolean upLoadFile(String path,String filename, InputStream is){ if(channelSftp == null){ logger.debug("初始化sftp串連:串連地址:{}",host); connect(); logger.trace("sftp串連初始化完成:{}",host); } try { validatePath(path); channelSftp.put(is,filename); disconnect(); } catch (SftpException e) { logger.error("檔案上傳失敗:\n{}",e); return false; } return true; } /** * 驗證伺服器檔案夾路徑,如不存在則建立 * @param path */ private void validatePath(String path) throws SftpException { try { channelSftp.lstat(path); channelSftp.cd(path); } catch (SftpException e) { if(NO_SUCH_FILE.equals(e.getMessage())){ logger.debug("{} 不存在,建立該路徑",path); String[] paths = path.split("/"); for(String p : paths){ try { channelSftp.cd(p); } catch (SftpException e1) { channelSftp.mkdir(p); channelSftp.cd(p); } } }else { throw e; } } } /** * 下載檔案 * @param path * @param filename * @param: is * @return */ public InputStream downFile(String path,String filename){ if(channelSftp == null){ logger.debug("初始化sftp串連:串連地址:{}",host); connect(); logger.trace("sftp串連初始化完成:{}",host); } try { channelSftp.cd(path); InputStream is= channelSftp.get(filename); disconnect(); return is; } catch (SftpException e) { return null; } }}
JSCH實現檔案上傳下載至sftp伺服器