JAVASFTP⽂件上传、下载及批量下载实例
1.jsch官⽅API查看地址(附件为需要的jar)
2.jsch简介
JSch(Java Secure Channel)是⼀个SSH2的纯Java实现。它允许你连接到⼀个SSH服务器,并且可以使⽤端⼝转发,X11转发,⽂件传输等,当然你也可以集成它的功能到你⾃⼰的应⽤程序。
SFTP(Secure File Transfer Protocol)安全⽂件传送协议。可以为传输⽂件提供⼀种安全的加密⽅法。SFTP 为 SSH的⼀部份,是⼀种传输⽂件到服务器的安全⽅式,但是传输效率⽐普通的FTP要低。
3.api常⽤的⽅法:
put():⽂件上传
get():⽂件下载
cd():进⼊指定⽬录
ls():得到指定⽬录下的⽂件列表
rename():重命名指定⽂件或⽬录
rm():删除指定⽂件
mkdir():创建⽬录
rmdir():删除⽬录
put和get都有多个重载⽅法,⾃⼰看源代码
4.对常⽤⽅法的使⽤,封装成⼀个util类
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import org.apache.log4j.Logger;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.ChannelSftp.LsEntry;
/**
* sftp⼯具类
*
* @author xxx
* @date 2014-6-17
* @time 下午1:39:44
* @version 1.0
*/
public class SFTPUtils
{
private static Logger log = Logger(Name());
private String host;//服务器连接ip
private String username;//⽤户名
private String password;//密码
private int port = 22;//端⼝号
private ChannelSftp sftp = null;
private Session sshSession = null;
public SFTPUtils(){}
public SFTPUtils(String host, int port, String username, String password)
{
this.host = host;
public SFTPUtils(String host, String username, String password) {
this.host = host;
this.username = username;
this.password = password;
}
/**
* 通过SFTP连接服务器
*/
public void connect()
{
try
{
JSch jsch = new JSch();
sshSession = Session(username, host, port);
if (log.isInfoEnabled())
{
log.info("Session created.");
}
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
if (log.isInfoEnabled())
{
log.info("Session connected.");
}
Channel channel = sshSession.openChannel("sftp");
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 disconnect()
{
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 remotPath:远程下载⽬录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/) * @param localPath:本地保存⽬录(以路径符号结束,D:\Duansha\sftp\)
* @param fileFormat:下载⽂件格式(以特定字符开头,为空不做检验)
* @param fileEndFormat:下载⽂件格式(⽂件格式)
* @param del:下载后是否删除sftp⽂件
* @return
*/
public List<String> batchDownLoadFile(String remotePath, String localPath,
String fileFormat, String fileEndFormat, boolean del)
{
List<String> filenames = new ArrayList<String>();
try
{
// connect();
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 = Filename();
SftpATTRS attrs = Attrs();
if (!attrs.isDir())
{
boolean flag = false;
String localFileName = localPath + filename;
fileFormat = fileFormat == null ? "" : fileFormat
.trim();
fileEndFormat = fileEndFormat == null ? ""
: im();
// 三种情况
if (fileFormat.length() > 0 && fileEndFormat.length() > 0)
connect下载{
if (filename.startsWith(fileFormat) && dsWith(fileEndFormat))
{
flag = downloadFile(remotePath, filename,localPath, filename);
if (flag)
{
filenames.add(localFileName);
if (flag && del)
{
deleteSFTP(remotePath, filename);
}
}
}
}
else if (fileFormat.length() > 0 && "".equals(fileEndFormat))
{
if (filename.startsWith(fileFormat))
{
flag = downloadFile(remotePath, filename, localPath, filename);
if (flag)
{
filenames.add(localFileName);
if (flag && del)
{
deleteSFTP(remotePath, filename);
}
}
}
}
else if (fileEndFormat.length() > 0 && "".equals(fileFormat))
{
if (dsWith(fileEndFormat))
{
flag = downloadFile(remotePath, filename,localPath, filename);
filenames.add(localFileName);
if (flag && del)
{
deleteSFTP(remotePath, filename);
}
}
}
}
else
{
flag = downloadFile(remotePath, filename,localPath, filename);
if (flag)
{
filenames.add(localFileName);
if (flag && del)
{
deleteSFTP(remotePath, filename);
}
}
}
}
}
}
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 remotPath:远程下载⽬录(以路径符号结束)
* @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);
<(remotePath + remoteFileName, fieloutput);
if (log.isInfoEnabled())
{
log.info("===DownloadFile:" + remoteFileName + " success from sftp.");
}
return true;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (SftpException e)
{
e.printStackTrace();
}
finally
{
try
{
fieloutput.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
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);
return true;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (SftpException e)
{
e.printStackTrace();
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return false;
}
/**
* 批量上传⽂件
* @param remotePath:远程保存⽬录
* @param localPath:本地上传⽬录(以路径符号结束)
* @param del:上传后是否删除本地⽂件
* @return
*/
public boolean bacthUploadFile(String remotePath, String localPath,
boolean del)
{
try
{
connect();
File file = new File(localPath);
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++)
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论