写在前面:
linux一般自带sftp,而windows需要先搭建sftp服务器,比如freesshd,http://www.freesshd.com/?ctt=download,搭建好sftp服务后再用java程序连接进行上传下载操作,需要特别注意的是用java上传到windows的sftp时的上传路径,freesshd搭建sftp时会有个sftp home path,假如设置的是D:\sftpupload,如果要上传到D:\sftpupload\test,那么代码中的上传路径设置为"/test"即可,一定要带/
依赖包
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
工具类
package xxx.utils;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Properties;
import java.util.Vector;
public class SftpUtil {
private static Logger logger = LoggerFactory.getLogger(SftpUtil.class);
/**
*
* @param filePath 文件全路径
* @param ftpPath 上传到目的端目录
* @param username
* @param password
* @param host
* @param port
*/
public static void uploadFile(String filePath, String ftpPath, String username, String password, String host, Integer port) {
FileInputStream input = null;
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
//获取session 账号-ip-端口
com.jcraft.jsch.Session sshSession = jsch.getSession(username, host, port);
//添加密码
sshSession.setPassword(password);
Properties sshConfig = new Properties();
//严格主机密钥检查
sshConfig.put("StrictHostKeyChecking", "no");
// sshConfig.put("kex", "diffie-hellman-group1-sha1,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha1,diffie-hellman-group-exchange-sha256");
sshSession.setConfig(sshConfig);
//开启session连接
sshSession.connect();
//获取sftp通道
sftp = (ChannelSftp) sshSession.openChannel("sftp");
//开启
sftp.connect();
//文件乱码处理
/*Class<ChannelSftp> c = ChannelSftp.class;
Field f = c.getDeclaredField("server_version");
f.setAccessible(true);
f.set(sftp, 2);
sftp.setFilenameEncoding("GBK");*/
File file = new File(filePath);
copyFile(sftp,file,ftpPath);
logger.info("================SFTP上传成功!==================");
} catch (Exception e) {
logger.error("================SFTP上传失败!==================");
e.printStackTrace();
}
}
public static void copyFile(ChannelSftp sftp, File file, String pwd) {
if (file.isDirectory()) {
File[] list = file.listFiles();
String fileName = file.getName();
try {
try {
try {
sftp.cd(pwd);
} catch (SftpException e) {
sftp.mkdir(pwd);
logger.info("上传根目录创建成功:" + pwd);
sftp.cd(pwd);
}
Vector ls = sftp.ls(fileName);
} catch (Exception e) {
sftp.mkdir(fileName);
System.out.println("目录创建成功:" + sftp.pwd() + "/" + fileName);
}
pwd = pwd + "/" + fileName;
try {
sftp.cd(fileName);
} catch (SftpException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < list.length; i++) {
copyFile(sftp, list[i], pwd);
}
} else {
try {
sftp.cd(pwd);
} catch (SftpException e1) {
e1.printStackTrace();
}
System.out.println("正在复制文件:" + file.getAbsolutePath());
InputStream instream = null;
OutputStream outstream = null;
try {
outstream = sftp.put(file.getName());
instream = new FileInputStream(file);
byte b[] = new byte[1024];
int n;
try {
while ((n = instream.read(b)) != -1) {
outstream.write(b, 0, n);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (SftpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
outstream.flush();
outstream.close();
instream.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
/**
* @param directory SFTP服务器的文件路径
* @param downloadFile SFTP服务器上的文件名
* @param saveFile 保存到本地路径
* @param username
* @param password
* @param host
* @param port
*/
public static void downloadFile(String directory, String downloadFile, String saveFile, String username, String password, String host, Integer port) {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
//获取session 账号-ip-端口
com.jcraft.jsch.Session sshSession = jsch.getSession(username, host, port);
//添加密码
sshSession.setPassword(password);
Properties sshConfig = new Properties();
//严格主机密钥检查
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
//开启session连接
sshSession.connect();
//获取sftp通道
sftp = (ChannelSftp) sshSession.openChannel("sftp");
//开启
sftp.connect();
if (directory != null && !"".equals(directory)) {
sftp.cd(directory);
}
FileOutputStream output = new FileOutputStream(new File(saveFile));
sftp.get(downloadFile, output);
output.close();
sftp.disconnect();
sshSession.disconnect();
System.out.println("================下载成功!==================");
} catch (SftpException | FileNotFoundException | JSchException e) {
logger.error("SFTP文件下载异常!", e);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String source = "D:\\test\\1";
String windowsDest = "/";
String linuxDest = "/home/sftp";
uploadFile(source ,windowsDest,"administrator" , "123123","192.168.1.69" ,5555 );
uploadFile(source ,linuxDest,"root" , "123123","192.168.1.67" ,22 );
}
}