import java.util.HashMap;
import java.util.Map;
public class SFTPGetTest {
public static final String SFTP_REQ_HOST = "host";
public static final String SFTP_REQ_PORT = "port";
public static final String SFTP_REQ_USERNAME = "username";
public static final String SFTP_REQ_PASSWORD = "password";
public static final int SFTP_DEFAULT_PORT = 22;
public static final String SFTP_REQ_LOC = "location";
public static void main(String[] args) throws Exception {
Map<String, String> sftpDetails = new HashMap<String, String>();
// 设置主机ip,端口,用户名,密码
sftpDetails.put(SFTP_REQ_HOST, "127.0.01");
sftpDetails.put(SFTP_REQ_USERNAME, "root");
sftpDetails.put(SFTP_REQ_PASSWORD, "123456");
sftpDetails.put(SFTP_REQ_PORT, "22");
String filename = "/home/img/11jpg.zip";// 目标文件名dst
String dst = "F:\\project\\11jpg.zip";// 本地文件名
SFTPFileOperation sftpopr = new SFTPFileOperation();
String ftpHost = sftpDetails.get(SFTP_REQ_HOST);
String port = sftpDetails.get(SFTP_REQ_PORT);
String ftpUserName = sftpDetails.get(SFTP_REQ_USERNAME);
String ftpPassword = sftpDetails.get(SFTP_REQ_PASSWORD);
sftpopr.getSFTPConnection(ftpHost,ftpUserName,ftpPassword,Integer.parseInt(port));
sftpopr.openChannel("sftp");
boolean isSavedSuccess = sftpopr.saveFiles("/home/img", filename, dst);
if(isSavedSuccess){
System.out.println("end");
sftpopr.closeChannel();
}
}
}
package com.longyg.sftp;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.Vector;
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 访问服务器的封装类
*
*/
public class SFTPFileOperation {
public static final int PORTNUM = 22;
public static final int TIMEOUT = 50000;
private Session session = null;
private ChannelSftp channel = null;
/**
* 连接SFTP
*
* @param host
* @param username
* @param pwd
* @return
* @throws JSchException
*/
public Session getSFTPConnection(String host, String username, String pwd) throws JSchException {
return this.getSFTPConnection(host, username, pwd, PORTNUM, TIMEOUT, false, true);
}
/**
* 连接SFTP
*
* @param host
* @param username
* @param pwd
* @param port
* @return
* @throws JSchException
*/
public Session getSFTPConnection(String host, String username, String pwd, int port) throws JSchException {
return this.getSFTPConnection(host, username, pwd, port, TIMEOUT, false, true);
}
/**
* 获得sftp 服务器的连接
*
* @param config
* 用户名 密码 端口号 主机名 等相关参数的封装
* @return session 连接的会话
* @throws JSchException
*/
public Session getSFTPConnection(String host, String username, String pwd, int port, int timeout,
boolean hostkeycheckBl, boolean pwdAuthenBl) throws JSchException {
JSch jsch = new JSch(); // 创建JSch对象
// 根据用户名,主机ip,端口获取一个Session对象
session = jsch.getSession(username, host, port);
java.util.Properties property = new java.util.Properties();
property.put("StrictHostKeyChecking", (hostkeycheckBl ? "yes" : "no"));
property.put("PasswordAuthentication", (pwdAuthenBl ? "yes" : "no"));
session.setConfig(property);
if (pwd != null && !pwd.equals(""))
session.setPassword(pwd);
if (timeout > 0)
session.setTimeout(timeout);
session.connect();
return session;
}
/**
* 打开一个频道
*
* @param session
* 会话 channelname 频道名称
* @return channel 频道
* @throws JSchException
*/
public ChannelSftp openChannel(String channelname) throws JSchException {
channel = (ChannelSftp) session.openChannel(channelname);
channel.connect();
return channel;
}
public boolean saveFiles(String directory, String downloadFile, String saveFile) {
boolean isSavedSuccess = false;
final String xFunctionName = "saveFiles";
try {
File file = new File(saveFile);
FileOutputStream fileOutputStream = new FileOutputStream(file);
channel.cd(directory);
channel.get(downloadFile, fileOutputStream);
fileOutputStream.close();
fileOutputStream = null;
file = null;
isSavedSuccess = true;
} catch (Exception e) {
return false;
}
return isSavedSuccess;
}
public boolean downLoadFile(String remoteDir, String fileName, String localFilePath) {
return downLoadFile(remoteDir, fileName, localFilePath, false);
}
/**
*
* 下载单个文件
*
* @param remoteDir
* @param fileName
* @param localFilePath
* @return
*/
public boolean downLoadFile(String remoteDir, String fileName, String localFilePath, boolean needDelete) {
boolean isDownloadSuccess = false;
final String xFunctionName = "downLoadFile";
FileOutputStream fileOutputStream = null;
File file = null;
try {
if(!channel.isConnected()){
this.openChannel("sftp");
}
file = new File(localFilePath);
if(!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
fileOutputStream = new FileOutputStream(file);
channel.cd(remoteDir);
channel.get(fileName, fileOutputStream);
isDownloadSuccess = true;
if(needDelete) {
deleteFile(remoteDir, fileName);
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
if(null != fileOutputStream){
fileOutputStream.close();
fileOutputStream = null;
}
if(null != file){
file = null;
}
this.disConnect();
} catch (Exception e2) {
}
}
return isDownloadSuccess;
}
public void downLoadDirectory(String remoteDir, String localFilePath, boolean needDelete) {
String xFunctionName = "downLoadDirectory";
FileOutputStream fileOutputStream = null;
File file = null;
try {
if(!channel.isConnected()){
this.openChannel("sftp");
}
Vector<LsEntry> files = getFileList(remoteDir);
Iterator<LsEntry> iter = files.iterator();
while(iter.hasNext()) {
LsEntry entry = iter.next();
if(!entry.getAttrs().isDir()) {
// downLoadFile(remoteDir, entry.getFilename(), localFilePath + "/" + entry.getFilename(), needDelete);
file = new File(localFilePath, entry.getFilename());
if(!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
fileOutputStream = new FileOutputStream(file);
channel.cd(remoteDir);
channel.get(entry.getFilename(), fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
fileOutputStream = null;
if(needDelete) {
deleteFile(remoteDir, entry.getFilename());
}
}
}
} catch (Exception e) {
} finally {
try {
if(null != fileOutputStream){
fileOutputStream.flush();
fileOutputStream.close();
fileOutputStream = null;
}
if(null != file){
file = null;
}
this.disConnect();
} catch (Exception e2) {
}
}
}
/**
*
*/
private void disConnect() {
channel.exit();
session.disconnect();
}
public String upload(String directory, String uploadFile) {
String xFunctionName = "upload";
String rspMsg = "";
try {
channel.cd(directory);
File file = new File(uploadFile);
FileInputStream fileInputStream = new FileInputStream(file);
channel.put(new FileInputStream(file), file.getName());
fileInputStream.close();
fileInputStream = null;
file = null;
} catch (Exception e) {
rspMsg = e.toString();
}
return rspMsg;
}
/**
* sftp上传
* @param directory
* @param uploadFile
* @param filename 上传临时文件名
* @return
*/
public String upload(String directory, String uploadFile, String filename) {
String xFunctionName = "upload";
String rspMsg = "";
try {
channel.cd(directory);
File file = new File(uploadFile);
FileInputStream fileInputStream = new FileInputStream(file);
channel.put(new FileInputStream(file), filename);
fileInputStream.close();
fileInputStream = null;
file = null;
} catch (Exception e) {
rspMsg = e.toString();
}
return rspMsg;
}
public Vector<LsEntry> getFileList(String directory) {
String xFunctionName = "getFileList";
Vector<LsEntry> vector = null;
try {
vector = channel.ls(directory);
} catch (SftpException e) {
}
return vector;
}
public boolean reNameFile(String directory, String oldName, String newName) {
String xFunctionName = "reNameFile";
boolean renameResult = false;
try {
channel.cd(directory);
channel.rename(oldName, newName);
renameResult = true;
} catch (SftpException e) {
}
return renameResult;
}
public boolean deleteFile(String directory, String filename) {
String xFunctionName = "deleteFile";
boolean result = false;
try {
channel.cd(directory);
channel.rm(filename);
channel.cd("/");
result = true;
} catch (SftpException e) {
}
return result;
}
public boolean isConnected() {
return session.isConnected();
}
/**
* 删除目录
*
* @param directory
* @param dirName
* @return
*/
public boolean deleteFilePath(String directory, String dirName) {
String xFunctionName = "deleteFilePath";
boolean result = false;
try {
channel.cd(directory);
channel.rmdir(dirName);
channel.cd("/");
result = true;
} catch (SftpException e) {
}
return result;
}
public void closeConnection() {
channel.disconnect();
session.disconnect();
}
public void closeChannel() {
channel.disconnect();
}
}