public class SFTPUtils {
private static Logger logger = Logger.getLogger(SFTPUtils.class);
private String host;
private Integer port;
private String username;
private String password;
private ChannelSftp sftp = null;
private Session sshSession = null; public SFTPUtils(String host, Integer port, String username, String password) { this.host = host;
this.port = port;
this.username = username;
this.password = password;
} /**
 * 
 * <p>
 * Title: connect
 * </p>
 * <p>
 * Description: 通过sftp连接服务器
 * </p>
 */
public void connect() {
try {
JSch jsch = new JSch();
sshSession = jsch.getSession("admin", "127.0.0.1", 50000);
if (logger.isInfoEnabled()) {
logger.info("Session created.");
}
sshSession.setPassword("admin");
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect(); if (logger.isInfoEnabled()) {
logger.info("Session connected.");
} Channel channel = sshSession.openChannel("sftp");
channel.connect(); if (logger.isInfoEnabled()) {
logger.info("opening channel.");
} sftp = (ChannelSftp) channel; if (logger.isInfoEnabled()) {
logger.info("connected to" + host + " .");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} /**
 * 
 * <p>
 * Title: disconnect
 * </p>
 * <p>
 * Description: 断开连接
 * </p>
 */
public void disconnect() {
if (this.sftp != null) {
if (this.sftp.isConnected()) {
this.sftp.disconnect();
if (logger.isInfoEnabled()) {
logger.info("sftp is closed already");
}
}
} if (this.sshSession != null) {
if (this.sshSession.isConnected()) {
this.sshSession.disconnect();
if (logger.isInfoEnabled()) {
logger.info("sshSesion is closed already");
}
}
}
}
    /**
     * 
     * <p>Title: uploadFile</p>  
     * <p>Description:上传单个文件 </p>  
     * @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);
return true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }
return false;
}

public boolean  batchUploadFile(String remotePath,String localPath,boolean del) {
connect();
File file=new File(localPath);
File[]  files=file.listFiles();
for (File file2 : files) {
if(file2.isFile()) {
uploadFile(remotePath, file2.getName(), localPath, file2.getName());
if(del) {
deleteFile(localPath+file2.getName());
}
}
}
return true;
} private boolean deleteFile(String localPath) {
// TODO Auto-generated method stub
File file=new File(localPath);
if(!file.exists()) {
return false;
}
if(!file.isFile()) {
return false;
}
file.delete();
return true;
}
    public boolean downloadFile(String remotePath,String remoteFileName,String localPath,String localFileName) {
     FileOutputStream out=null;
     try {
     File file =new File(localPath+localFileName);
     File parentFile=file.getParentFile();
     if(!parentFile.exists()) {
     parentFile.mkdirs();
     }
     if(!file.exists()) {
     file.createNewFile();
     }
     out=new FileOutputStream(file);
     sftp.get(remotePath+remoteFileName, out);
     return true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(out!=null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
     return false;
    }
    
    public boolean batchDownLoadFile(String remotePath,String localPath,String fileFormat,boolean del) {
     try {
     File directory=new File(localPath);
     if(!directory.exists()) {
     directory.mkdirs();
     }
@SuppressWarnings("rawtypes")
Vector v=listFiles(remotePath);
if(v.size()>0) {
@SuppressWarnings("rawtypes")
Iterator iterator=v.iterator();
while(iterator.hasNext()) {
LsEntry lsEntry=(LsEntry) iterator.next();
String filename=lsEntry.getFilename();
SftpATTRS attrs=lsEntry.getAttrs();
if(!attrs.isDir()) {
if(fileFormat!=null && !"".equals(fileFormat)) {
if(filename.startsWith(fileFormat)) {
if(downloadFile(remotePath, filename, localPath, filename) && del) {
deleteSFTPFile(remotePath, filename);
}
}
}else {
if(downloadFile(remotePath, filename, localPath, filename) && del) {
deleteSFTPFile(remotePath,filename);
}
}
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
     return false;
    }
private void deleteSFTPFile(String directory, String deleteFile) {
// TODO Auto-generated method stub
try {
sftp.cd(directory);
sftp.rm(deleteFile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} @SuppressWarnings("rawtypes")
private Vector listFiles(String remotePath) throws SftpException {
// TODO Auto-generated method stub
return sftp.ls(remotePath);
} private boolean createDir(String remotePath) {
// TODO Auto-generated method stub
try {
if (isDirExist(remotePath)) {
this.sftp.cd(remotePath);
return true;
}
String pathArray[] = remotePath.split("/");
StringBuffer filePath = new StringBuffer("/");
for (String path : pathArray) {
if ("".equals(path)) {
continue;
}
filePath.append(path).append("/");
if (isDirExist(filePath.toString())) {
sftp.cd(filePath.toString());
} else {
sftp.mkdir(filePath.toString());
sftp.cd(filePath.toString());
}
this.sftp.cd(remotePath);
return true;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
} private boolean isDirExist(String remotePath) {
// TODO Auto-generated method stub
boolean flag = false;
try {
SftpATTRS sftpATTRS = sftp.lstat(remotePath);
flag = true;
return sftpATTRS.isDir();
} catch (Exception e) {
// TODO Auto-generated catch block
if (e.getMessage().toLowerCase().equals("no such file")) {
flag = false;
}
}
return flag;
}

public static void main(String[] args) {
SFTPUtils sFTPUtils=new SFTPUtils("127.0.0.1", 50000, "admin", "admin");
sFTPUtils.connect();
//sFTPUtils.uploadFile("", "123.pdf", "F:", "1.pdf");
//sFTPUtils.batchUploadFile("2/", "F:\\2\\", true);
//sFTPUtils.downloadFile("/", "123.pdf", "E:", "2.pdf");
sFTPUtils.batchDownLoadFile("2/", "F:/3/", "", true);
sFTPUtils.disconnect();
}
}