当前位置:网站首页>Play SFTP upload file
Play SFTP upload file
2022-06-28 09:03:00 【Endless learning WangXiaoShuai】
First, let's look at the requirements , Let's do one and put the data we find in dat In the closing document , And the format of the file is unix The format of , Reuse linux How to pack in the future , Package as with gz Final document , And then upload it to sftp The specified location on the server .
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");
// Here is to specify the relative path , Then add the format of the date , As a mark to distinguish files
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();
}
// Write with buffer
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");// This is to turn into unix The way , because windows Next is "\r\n", It's also the default way , You can also use it 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();
// Get the absolute path and act as gz pack
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);
// Errors will be reported during production , because "\\" stay windows I can , But in linux No way , In order to be universally applicable to automatic adaptation , therefore
sftp.upload("/data/works", s.substring(s.lastIndexOf(File.separator)+1), is);
}
}catch (Exception e){
e.printStackTrace();
}finally {
sftp.logout();
}
}
there host and port Enter your own server ip And port number .
Here is the tool class code :
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 Login username */
private String username;
/** FTP The login password */
private String password;
/** Private key */
private String privateKey;
/** FTP Server address IP Address */
private String host;
/** FTP port */
private int port;
/**
* Construct a password based authentication system sftp object
* @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;
}
/**
* Construct an authentication based on secret key sftp object
* @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(){}
/**
* Connect sftp The server
*
* @throws Exception
*/
public void login(){
try {
JSch jsch = new JSch();
if (privateKey != null) {
jsch.addIdentity(privateKey);// Set up the private key
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()});
}
}
/**
* Close the connection 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");
}
}
}
/**
* Upload the data of the input stream to sftp As a document
*
* @param directory
* Upload to this directory
* @param sftpFileName
* sftp Client file name
* @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);
}
/**
* Upload a single file
*
* @param directory
* Upload to sftp Catalog
* @param uploadFile
* Files to upload , Including paths
* @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));
}
/**
* take byte[] Upload to sftp, As a document . Be careful : from String Generate byte[] yes , To specify a character set .
*
* @param directory
* Upload to sftp Catalog
* @param sftpFileName
* The file in sftp End naming
* @param byteArr
* Byte array to upload
* @throws SftpException
* @throws Exception
*/
public void upload(String directory, String sftpFileName, byte[] byteArr) throws SftpException{
upload(directory, sftpFileName, new ByteArrayInputStream(byteArr));
}
/**
* Upload the string to according to the specified character encoding sftp
*
* @param directory
* Upload to sftp Catalog
* @param sftpFileName
* The file in sftp End naming
* @param dataStr
* Data to be uploaded
* @param charsetName
* sftp File on , Save with this character code
* @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)));
}
/**
* Download the file
*
* @param directory
* Download directory
* @param downloadFile
* Downloaded files
* @param saveFile
* There is a local path
* @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);
}
/**
* Download the file
* @param directory Download directory
* @param downloadFile Download file name
* @return Byte array
* @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;
}
/**
* Delete file
*
* @param directory
* To delete the directory where the file is located
* @param deleteFile
* Files to delete
* @throws SftpException
* @throws Exception
*/
public void delete(String directory, String deleteFile) throws SftpException {
sftp.cd(directory);
sftp.rm(deleteFile);
}
/**
* List the files in the directory
*
* @param directory
* Directory to list
* @param
* @return
* @throws SftpException
*/
public Vector<?> listFiles(String directory) throws SftpException {
return sftp.ls(directory);
}
public static void isExistDir(String filePath) {
String paths[] = {""};
// Cutting path
try {
String tempPath = new File(filePath).getCanonicalPath();//File Objects are converted to standard paths and cut , There are two kinds of windows and linux
paths = tempPath.split("\\\\");//windows
if(paths.length==1){paths = tempPath.split("/");}//linux
} catch (IOException e) {
System.out.println(" Cutting path error ");
e.printStackTrace();
}
// Determine whether there is a suffix
boolean hasType = false;
if(paths.length>0){
String tempPath = paths[paths.length-1];
if(tempPath.length()>0){
if(tempPath.indexOf(".")>0){
hasType=true;
}
}
}
// Create folder
String dir = paths[0];
for (int i = 0; i < paths.length - (hasType?2:1); i++) {// Note the length of the loop here , The suffix is the file path , If there is no folder path
try {
dir = dir + "/" + paths[i + 1];// use linux The standard writing under , because windows Such paths can be identified , Therefore, the writing method of police appearance is adopted here
File dirFile = new File(dir);
if (!dirFile.exists()) {
dirFile.mkdir();
System.out.println(" Directory created successfully :" + dirFile.getCanonicalFile());
}
} catch (Exception e) {
System.err.println(" Exception occurred in folder creation ");
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 Add the following dependencies to the file :
<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>
Okay , End of explanation , thank you .
边栏推荐
- MATLAB小技巧(20)矩阵分析--主成分回归
- Copy & Deepcopy
- Construire le premier réseau neuronal avec pytorch et optimiser
- spark的资源调度和任务调度
- Tree
- 【大案例】学成在线网站
- It only takes two steps to find the right PMP organization, one check and two questions
- Ffmpeg streaming fails to update header with correct duration
- Common tools for interface testing --postman
- [untitled]
猜你喜欢
Chrome devtools
SQL 优化经历:从 30248秒到 0.001秒的经历
Postman interface test
"Jianzhi offer" -- Interview Question 4: finding two-dimensional arrays
spark的资源调度和任务调度
Operating principle of Rogowski coil
[cloud native | kubernetes] in depth understanding of pod (VI)
Apache Doris becomes the top project of Apache
罗氏线圈工作原理
SQL 優化經曆:從 30248秒到 0.001秒的經曆
随机推荐
MATLAB小技巧(20)矩阵分析--主成分回归
Import and export of a single collection in postman
理解IO模型
break database---mysql
【.NET6】gRPC服务端和客户端开发案例,以及minimal API服务、gRPC服务和传统webapi服务的访问效率大对决
Chrome devtools
Lilda low code data large screen, leveling the threshold of data application development
Common test method used by testers --- orthogonal method
网上炒股开户安不安全?
SQL optimization experience: from 30248 seconds to 0.001 seconds
spark的资源调度和任务调度
DEJA_ Vu3d - 052 of cesium feature set - Simulation of satellite orbit (high altitude) effect
Postman interface test
Which securities company is better and safer to choose when opening an account for the inter-bank certificate of deposit fund with mobile phone
Superimposed ladder diagram and line diagram and merged line diagram and needle diagram
[untitled]
实现全局双指长按返回桌面
Ffmpeg streaming fails to update header with correct duration
[cloud native | kubernetes] in depth understanding of pod (VI)
Implementation of single sign on