当前位置:网站首页>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 .
边栏推荐
- 如何抑制SiC MOSFET Crosstalk(串扰)?
- containerd1.5.5的安装
- 为什么SELECT * 会导致查询效率低?
- DEJA_ Vu3d - 051 of cesium function set - perfect realization of terrain excavation
- webrtc优势与模块拆分
- A - deep sea exploration
- Webrtc advantages and module splitting
- Rman Backup Report Ora - 19809 Ora - 19804
- 股票 停牌
- Mysql8.0 forgot the root password
猜你喜欢

Using transform:scale causes the page mouse hover event to disappear

Application of energy management system in iron and steel enterprises

Data mining modeling practice

rman备份报ORA-19809 ORA-19804

【大案例】学成在线网站

containerd1.5.5的安装

硬盘基本知识(磁头、磁道、扇区、柱面)

How to solve the problem of high concurrency and seckill

Which is a better ERP management system for electronic component sales?

Assertions used in the interface automation platform
随机推荐
批量修改表和表中字段排序规则
APICloud携手三六零天御,助力企业守好App安全“第一关”
From knowledge to wisdom: how far will the knowledge map go?
与普通探头相比,差分探头有哪些优点
[go ~ 0 to 1] the third day June 27 slice, map and function
JMeter -- interface test 2
[untitled]
Avframe Memory Management API
SQL注入之文件读写
Why does select * lead to low query efficiency?
Maintenance and protection of common faults of asynchronous motor
电子元器件销售ERP管理系统哪个比较好?
怎样在手机上开户?现在网上开户安全么?
rman備份報ORA-19809 ORA-19804
webrtc优势与模块拆分
AVFrame内存管理api
学习阿里如何进行数据指标体系的治理
Applet: traverse the value of an array in the list, which is equivalent to for= "list" list An item in comment
状态机程序框架
Implement global double finger long press to return to the desktop