首先看一下需求,让做一个把查到的数据放在以dat结尾的文件里,而且文件的格式是unix的格式,再使用linux下的打包方式,打包为以gz结尾的文件,然后再上传到sftp服务器的指定位置上。
public static void main(String[] args) throws SftpException, IOException {
List<String> push_messageList=new ArrayList<>();
List<String> push_trackList=new ArrayList<>();
push_messageList.add("messageqweqwe");
push_messageList.add("12345");
push_trackList.add("trackqewqweq");
push_trackList.add("12345");
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
//这里是指定相对路径,然后添加日期的格式,作为区分文件的标志
File push_message = new File("resourceSftp/push_message_"+df.format(new Date())+".dat");
File push_track = new File("resourceSftp/push_track_"+df.format(new Date())+".dat");
String parent = push_message.getParent();
File file = new File(parent);
if(!file.exists()){
file.mkdirs();
}
//使用缓冲写入
BufferedWriter bw=new BufferedWriter(new FileWriter(push_message));
BufferedWriter bw1=new BufferedWriter(new FileWriter(push_track));
for (String message:
push_messageList) {
bw.write(message+"\n");//这是转为unix的方式,因为windows下是"\r\n",也是默认的方式,当然也可以使用bw.newLine()。
bw.flush();
}
for (String track:
push_trackList) {
bw1.write(track+"\n");
bw1.flush();
}
bw1.close();
bw.close();
String push_messageAbsolutePath = push_message.getAbsolutePath();
//获取到绝对路径然后作为gz打包
try (FileOutputStream fileOutputStream = new FileOutputStream(push_messageAbsolutePath+".gz");
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(fileOutputStream)) {
FileInputStream fileInputStream = new FileInputStream(push_messageAbsolutePath);
byte[] b = new byte[1024*1024*5];
int length = 0;
while ((length = fileInputStream.read(b)) != -1) {
gzipOutputStream.write(b, 0, length);
}
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
String push_trackAbsolutePath = push_track.getAbsolutePath();
try (FileOutputStream fileOutputStream = new FileOutputStream(push_trackAbsolutePath+".gz");
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(fileOutputStream)) {
FileInputStream fileInputStream = new FileInputStream(push_trackAbsolutePath);
byte[] b = new byte[1024*1024*5];
int length = 0;
while ((length = fileInputStream.read(b)) != -1) {
gzipOutputStream.write(b, 0, length);
}
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
List<String> list=new ArrayList<>();
list.add(push_messageAbsolutePath+".gz");
list.add(push_trackAbsolutePath+".gz");
SFTPUtil sftp = new SFTPUtil("root", "123456", host, port);
sftp.login();
try{
for (String s:
list) {
// uploadftp(s,s.substring(s.lastIndexOf("\\")+1));
File file1 = new File(s);
InputStream is = new FileInputStream(file1);
// sftp.upload("/data/works", s.substring(s.lastIndexOf("\\")+1), is);
//上到生产时候会报错,因为"\\"在windows下可以,但是在linux下不行,为了普遍适用自动适应,故此
sftp.upload("/data/works", s.substring(s.lastIndexOf(File.separator)+1), is);
}
}catch (Exception e){
e.printStackTrace();
}finally {
sftp.logout();
}
}
这里的host和port自行输入自己的服务器ip和端口号即可。
下面给出工具类代码:
import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.io.IOUtils;
public class SFTPUtil {
private transient Logger log = LoggerFactory.getLogger(this.getClass());
private ChannelSftp sftp;
private Session session;
/** FTP 登录用户名*/
private String username;
/** FTP 登录密码*/
private String password;
/** 私钥 */
private String privateKey;
/** FTP 服务器地址IP地址*/
private String host;
/** FTP 端口*/
private int port;
/**
* 构造基于密码认证的sftp对象
* @param
* @param password
* @param host
* @param port
*/
public SFTPUtil(String username, String password, String host, int port) {
this.username = username;
this.password = password;
this.host = host;
this.port = port;
}
/**
* 构造基于秘钥认证的sftp对象
* @param
* @param host
* @param port
* @param privateKey
*/
public SFTPUtil(String username, String host, int port, String privateKey) {
this.username = username;
this.host = host;
this.port = port;
this.privateKey = privateKey;
}
public SFTPUtil(){}
/**
* 连接sftp服务器
*
* @throws Exception
*/
public void login(){
try {
JSch jsch = new JSch();
if (privateKey != null) {
jsch.addIdentity(privateKey);// 设置私钥
log.info("sftp connect,path of private key file:{}" , privateKey);
}
log.info("sftp connect by host:{} username:{}",host,username);
session = jsch.getSession(username, host, port);
log.info("Session is build");
if (password != null) {
session.setPassword(password);
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
log.info("Session is connected");
Channel channel = session.openChannel("sftp");
channel.connect();
log.info("channel is connected");
sftp = (ChannelSftp) channel;
log.info(String.format("sftp server host:[%s] port:[%s] is connect successfull", host, port));
} catch (JSchException e) {
log.error("Cannot connect to specified sftp server : {}:{} \n Exception message is: {}", new Object[]{host, port, e.getMessage()});
}
}
/**
* 关闭连接 server
*/
public void logout(){
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
log.info("sftp is closed already");
}
}
if (session != null) {
if (session.isConnected()) {
session.disconnect();
log.info("sshSession is closed already");
}
}
}
/**
* 将输入流的数据上传到sftp作为文件
*
* @param directory
* 上传到该目录
* @param sftpFileName
* sftp端文件名
* @param
*
* @throws SftpException
* @throws Exception
*/
public void upload(String directory, String sftpFileName, InputStream input) throws SftpException{
try {
sftp.cd(directory);
} catch (SftpException e) {
log.warn("directory is not exist");
sftp.mkdir(directory);
sftp.cd(directory);
}
sftp.put(input, sftpFileName);
log.info("file:{} is upload successful" , sftpFileName);
}
/**
* 上传单个文件
*
* @param directory
* 上传到sftp目录
* @param uploadFile
* 要上传的文件,包括路径
* @throws FileNotFoundException
* @throws SftpException
* @throws Exception
*/
public void upload(String directory, String uploadFile) throws FileNotFoundException, SftpException{
File file = new File(uploadFile);
upload(directory, file.getName(), new FileInputStream(file));
}
/**
* 将byte[]上传到sftp,作为文件。注意:从String生成byte[]是,要指定字符集。
*
* @param directory
* 上传到sftp目录
* @param sftpFileName
* 文件在sftp端的命名
* @param byteArr
* 要上传的字节数组
* @throws SftpException
* @throws Exception
*/
public void upload(String directory, String sftpFileName, byte[] byteArr) throws SftpException{
upload(directory, sftpFileName, new ByteArrayInputStream(byteArr));
}
/**
* 将字符串按照指定的字符编码上传到sftp
*
* @param directory
* 上传到sftp目录
* @param sftpFileName
* 文件在sftp端的命名
* @param dataStr
* 待上传的数据
* @param charsetName
* sftp上的文件,按该字符编码保存
* @throws UnsupportedEncodingException
* @throws SftpException
* @throws Exception
*/
public void upload(String directory, String sftpFileName, String dataStr, String charsetName) throws UnsupportedEncodingException, SftpException{
upload(directory, sftpFileName, new ByteArrayInputStream(dataStr.getBytes(charsetName)));
}
/**
* 下载文件
*
* @param directory
* 下载目录
* @param downloadFile
* 下载的文件
* @param saveFile
* 存在本地的路径
* @throws SftpException
* @throws FileNotFoundException
* @throws Exception
*/
public void download(String directory, String downloadFile, String saveFile) throws SftpException, FileNotFoundException{
if (directory != null && !"".equals(directory)) {
sftp.cd(directory);
}
File file = new File(saveFile);
sftp.get(downloadFile, new FileOutputStream(file));
log.info("file:{} is download successful" , downloadFile);
}
/**
* 下载文件
* @param directory 下载目录
* @param downloadFile 下载的文件名
* @return 字节数组
* @throws SftpException
* @throws IOException
* @throws Exception
*/
public byte[] download(String directory, String downloadFile) throws SftpException, IOException{
if (directory != null && !"".equals(directory)) {
sftp.cd(directory);
}
InputStream is = sftp.get(downloadFile);
byte[] fileData = IOUtils.toByteArray(is);
log.info("file:{} is download successful" , downloadFile);
return fileData;
}
/**
* 删除文件
*
* @param directory
* 要删除文件所在目录
* @param deleteFile
* 要删除的文件
* @throws SftpException
* @throws Exception
*/
public void delete(String directory, String deleteFile) throws SftpException {
sftp.cd(directory);
sftp.rm(deleteFile);
}
/**
* 列出目录下的文件
*
* @param directory
* 要列出的目录
* @param
* @return
* @throws SftpException
*/
public Vector<?> listFiles(String directory) throws SftpException {
return sftp.ls(directory);
}
public static void isExistDir(String filePath) {
String paths[] = {""};
//切割路径
try {
String tempPath = new File(filePath).getCanonicalPath();//File对象转换为标准路径并进行切割,有两种windows和linux
paths = tempPath.split("\\\\");//windows
if(paths.length==1){paths = tempPath.split("/");}//linux
} catch (IOException e) {
System.out.println("切割路径错误");
e.printStackTrace();
}
//判断是否有后缀
boolean hasType = false;
if(paths.length>0){
String tempPath = paths[paths.length-1];
if(tempPath.length()>0){
if(tempPath.indexOf(".")>0){
hasType=true;
}
}
}
//创建文件夹
String dir = paths[0];
for (int i = 0; i < paths.length - (hasType?2:1); i++) {// 注意此处循环的长度,有后缀的就是文件路径,没有则文件夹路径
try {
dir = dir + "/" + paths[i + 1];//采用linux下的标准写法进行拼接,由于windows可以识别这样的路径,所以这里采用警容的写法
File dirFile = new File(dir);
if (!dirFile.exists()) {
dirFile.mkdir();
System.out.println("成功创建目录:" + dirFile.getCanonicalFile());
}
} catch (Exception e) {
System.err.println("文件夹创建发生异常");
e.printStackTrace();
}
}
}
public static void uploadftp(String filePath,String ftpName) throws SftpException, IOException{
SFTPUtil sftp = new SFTPUtil("root", "123456", host, port);
sftp.login();
File file = new File(filePath);
InputStream is = new FileInputStream(file);
sftp.upload("/data/works", ftpName, is);
sftp.logout();
}
}
pom文件内加进以下依赖:
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.53</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
好了,讲解完毕,谢谢。