package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Properties;
import java.util.Vector;
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;
public class SFTPTest {
private String host;
private String username;
private String password;
private int port = 22;
private ChannelSftp sftp = null;
private Session sshSession = null;
public SFTPTest() {
}
public SFTPTest(String host, String username, String password, int port) {
this.host = host;
this.username = username;
this.password = password;
this.port = port;
}
public SFTPTest(String host, String username, String password) {
this.host = host;
this.username = username;
this.password = password;
}
/**
* connect server via sftp
*/
public void connect() {
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
sshSession = jsch.getSession(username, host, port);
System.out.println("Session created.");
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
System.out.println("Session connected.");
System.out.println("Opening Channel.");
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
System.out.println("Connected to " + host + ".");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 关闭资源
*/
public void disconnect() {
if (this.sftp != null) {
if (this.sftp.isConnected()) {
this.sftp.disconnect();
System.out.println("sftp is closed already");
}
}
if (this.sshSession != null) {
if (this.sshSession.isConnected()) {
this.sshSession.disconnect();
System.out.println("sshSession is closed already");
}
}
}
/**
* 批量下载文件
*
* @param remotPath
* 远程下载目录(以路径符号结束)
* @param localPath
* 本地保存目录(以路径符号结束)
* @param fileFormat
* 下载文件格式(以特定字符开头,为空不做检验)
* @param del
* 下载后是否删除sftp文件
* @return
*/
public boolean batchDownLoadFile(String remotPath, String localPath,
String fileFormat, boolean del) {
try {
connect();
Vector v = listFiles(remotPath);
if (v.size() > 0) {
Iterator it = v.iterator();
while (it.hasNext()) {
LsEntry entry = (LsEntry) it.next();
String filename = entry.getFilename();
SftpATTRS attrs = entry.getAttrs();
if (!attrs.isDir()) {
if (fileFormat != null && !"".equals(fileFormat.trim())) {
if (filename.startsWith(fileFormat)) {
if (this.downloadFile(remotPath, filename,
localPath, filename)
&& del) {
deleteSFTP(remotPath, filename);
}
}
} else {
if (this.downloadFile(remotPath, filename,
localPath, filename)
&& del) {
deleteSFTP(remotPath, filename);
}
}
}
}
}
} catch (SftpException e) {
e.printStackTrace();
} finally {
this.disconnect();
}
return false;
}
/**
* 下载单个文件
*
* @param remotPath
* 远程下载目录(以路径符号结束)
* @param remoteFileName
* 下载文件名
* @param localPath
* 本地保存目录(以路径符号结束)
* @param localFileName
* 保存文件名
* @return
*/
public boolean downloadFile(String remotePath, String remoteFileName,
String localPath, String localFileName) {
try {
sftp.cd(remotePath);
File file = new File(localPath + localFileName);
mkdirs(localPath + localFileName);
sftp.get(remoteFileName, new FileOutputStream(file));
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SftpException 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++) {
if (files[i].isFile()
&& files[i].getName().indexOf("bak") == -1) {
if (this.uploadFile(remotePath, files[i].getName(),
localPath, files[i].getName())
&& del) {
deleteFile(localPath + files[i].getName());
}
}
}
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
this.disconnect();
}
return false;
}
/**
* 删除本地文件
*
* @param filePath
* @return
*/
public boolean deleteFile(String filePath) {
File file = new File(filePath);
if (!file.exists()) {
return false;
}
if (!file.isFile()) {
return false;
}
return file.delete();
}
/**
* 创建目录
*
* @param createpath
* @return
*/
public boolean createDir(String createpath) {
try {
if (isDirExist(createpath)) {
this.sftp.cd(createpath);
return true;
}
String pathArry[] = createpath.split("/");
StringBuffer filePath = new StringBuffer("/");
for (String path : pathArry) {
if (path.equals("")) {
continue;
}
filePath.append(path + "/");
if (isDirExist(filePath.toString())) {
sftp.cd(filePath.toString());
} else {
// 建立目录
sftp.mkdir(filePath.toString());
// 进入并设置为当前目录
sftp.cd(filePath.toString());
}
}
this.sftp.cd(createpath);
return true;
} catch (SftpException e) {
e.printStackTrace();
}
return false;
}
/**
* 判断目录是否存在
*
* @param directory
* @return
*/
public boolean isDirExist(String directory) {
boolean isDirExistFlag = false;
try {
SftpATTRS sftpATTRS = sftp.lstat(directory);
isDirExistFlag = true;
return sftpATTRS.isDir();
} catch (Exception e) {
if (e.getMessage().toLowerCase().equals("no such file")) {
isDirExistFlag = false;
}
}
return isDirExistFlag;
}
/**
* 删除stfp文件
*
* @param directory
* 要删除文件所在目录
* @param deleteFile
* 要删除的文件
* @param sftp
*/
public void deleteSFTP(String directory, String deleteFile) {
try {
sftp.cd(directory);
sftp.rm(deleteFile);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 如果目录不存在就创建目录
*
* @param path
*/
public void mkdirs(String path) {
File f = new File(path);
String fs = f.getParent();
f = new File(fs);
if (!f.exists()) {
f.mkdirs();
}
}
/**
* 列出目录下的文件
*
* @param directory
* 要列出的目录
* @param sftp
* @return
* @throws SftpException
*/
public Vector listFiles(String directory) throws SftpException {
return sftp.ls(directory);
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public ChannelSftp getSftp() {
return sftp;
}
public void setSftp(ChannelSftp sftp) {
this.sftp = sftp;
}
public static void main(String[] args) {
SFTPTest ftp = new SFTPTest("127.0.0.1", "admin", "admin");
String localPath = "D:\\sftp\\";
String remotePath = "/home/itvsoap/file_interface/bill/lzj/test/";
ftp.connect();
ftp.uploadFile(remotePath, "test.txt", localPath, "test.txt");
//ftp.bacthUploadFile(remotePath,localPath,true);
// ftp.downloadFile(remotePath, "test.txt", localPath, "test.txt");
//ftp.batchDownLoadFile(remotePath, localPath, null, true);
ftp.disconnect();
System.exit(0);
}
}
相关推荐
java实现sftp上传下载文件,使用jcraft实现,含所需jar包。
本篇文章主要介绍了JAVA SFTP文件上传、下载及批量下载实例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
Java 操作SFTP上传文件下载案例,很值得看的,Java 操作SFTP上传文件下载案例,很值得看的。
jsch.jar java使用sftp实现上传下载文件 ,包含jar包 及 实现的工具类 ,供各位参考
JSch - Java实现的SFTP(文件上传详解篇)
写了一个java操作sftp的工具类,里面有上传、下载、批量操作、远程创建目录、删除文件等等方法。里面的方法,都经过我测试,可用。。
用jsch实现ftp上传整个文件夹,用jsch实现ftp上传整个文件夹,用jsch实现ftp上传整个文件夹,
java实现后端数据导出成csv文件并上传到指定的sftp服务器,主要是使用univocity-parsers来做的csv文件导出以及采用jsch来完成csv文件的sftp上传。
JAVA实现SFTP文件传输和下载,包含事例代码
适合java进行文件上传下载的童鞋们,常用方法已包装好,可直接使用。
jsch-0.1.53 不支持修改编码格式,sftp.setFilenameEncoding("GBK");这样修改是不起作用的,所以必须修改源码。此处是修改源码后重新导出的jar包。
java使用sftp实现文件的上传与分片上传
java编码,通过ftp和sftp连接linux服务器上次和下载文件。
csv导出使用的使用的是univocity-parsers的支持类库,sftp上传采用的是jsch的类库,两者结合实现了数据导出成csv文件并上传指定服务器
java 实现 sftp 文件上传下载 等操作。
工作中遇到客户提出的sftp上传,把核心代码给大家
NULL 博文链接:https://z-one.iteye.com/blog/1605049
主要介绍了Java使用SFTP上传文件到服务器的简单使用,非常不错,具有参考借鉴价值,需要的朋友可以参考下
java使用swing编写sfp文件与文件夹上传功能,后续给大家升级同时多个目标地址上传
1.依赖的jar文件 jsch-0.1.53.jar 2.登录方式有密码登录,和密匙登录 3.java如何实现sftp上传文件功能,内含详细代码