SFTP and FTP download files to the current service based on the configuration of the remote server address _java

Source: Internet
Author: User
Tags abstract addall

Needless to say, the key code looks like this:

Package com.eastrobot.remote; 
Import java.util.List; 
Import Java.util.concurrent.ExecutorService; 
Import java.util.concurrent.Executors; 
Import Org.apache.commons.logging.Log; 
Import Org.apache.commons.logging.LogFactory; 
Import Com.eastrobot.util.PropertiesUtil; /** * Full.zhang * * Ftp/sftp abstract Method Class */Public abstract class Fileremote {private static final String Ftp_mode = " 
FTP "; 
private static final String Sftp_mode = "SFTP"; 
public static String FTPRoot; 
public static String mode; 
public static String host; 
public static String username; 
public static String password; 
public static String port; 
private static Fileremote client = NULL; 
Maximum one-time download 50 files public static int max = 50; 
Private final static Log LOGGER = Logfactory.getlog (Fileremote.class); 
public static Fileremote getinstance () {if (client = null) {FTPRoot = propertiesutil.getstring ("Transfer.root"); 
mode = propertiesutil.getstring ("Transfer.mode"); Host = propertiesutil.getstring ("Transfer. Host "); 
Username = propertiesutil.getstring ("Transfer.username"); 
Password = propertiesutil.getstring ("Transfer.password"); 
Port = propertiesutil.getstring ("Transfer.port"); 
if (Mode.equals (Ftp_mode)) {client = new fileftpremote (); 
else if (mode.equals (Sftp_mode)) {client = new filesftpremote (); 
} return client; 
/** * Perform timed task */public void process () {logger.debug ("----------------------------------------Enter a timed download remote file"); 
Create a thread pool Executorservice exec = Executors.newsinglethreadexecutor (); 
Exec.execute (New Runnable () {@Override public void run () {//Establish a connection Initftpinfo (host, port, username, password); 
Remote service all source file path Sets list<string> Listsourcepath = Listremotefilepath (FTPRoot); 
if (Listsourcepath.isempty ()) {Logger.debug ("____________________ release Connection"); 
Client.closeconnection (); 
Return 
} if (Listsourcepath.size () > Max) {listsourcepath = listsourcepath.sublist (0, Max); 
for (String Path:listsourcepath) {downloadremotefile (path); } LoggEr.debug ("____________________ release Connection"); 
Client.closeconnection (); 
} 
}); 
Exec.shutdown ();  
/** * Initialize connection * @param host * @param port * @param username * @param password * @throws Exception * @return * * 
public abstract void Initftpinfo (string host, string port, string Username, string password); /** * Download remote service under File to local Service * * @param path * @return * @throws Exception/public abstract void Downloadremotefile (Strin 
G FilePath); /** * Gets all the file path collections under the specified directory under the remote service (containing the files under the subdirectory) * * @param path * @return/public abstract list<string> Listremotefile 
Path (String path); 
/** * FREE Connection * * public abstract void closeconnection (); 
[Java] View plain copy package com.eastrobot.remote; 
Import Java.io.File; 
Import Java.io.FileOutputStream; 
Import java.io.IOException; 
Import Java.io.OutputStream; 
Import java.util.ArrayList; 
Import java.util.List; 
Import Org.apache.commons.io.IOUtils; 
Import Org.apache.commons.lang.StringUtils; 
Import Org.apache.commons.logging.Log; ImpoRT org.apache.commons.logging.LogFactory; 
Import org.apache.commons.net.ftp.FTPClient; 
Import Org.apache.commons.net.ftp.FTPFile; 
Import org.apache.commons.net.ftp.FTPReply; 
Import Com.eastrobot.command.Commander; 
public class Fileftpremote extends Fileremote {protected ftpclient ftpclient; 
Private String encoding = "UTF-8"; 
Private Boolean binarytransfer = true; 
Private final static Log LOGGER = Logfactory.getlog (Fileftpremote.class); @Override public void Initftpinfo (string host, string port, string Username, string password) {try {//construct a ftpclient real 
Example ftpclient = new FtpClient (); 
Sets the character set ftpclient.setcontrolencoding (encoding); Connecting to the FTP server Ftpclient.connect (host, Stringutils.isnotblank (port)? 
Integer.valueof (port): 21); 
Check the return code after connection to verify the success of the connection int reply = Ftpclient.getreplycode (); 
if (ftpreply.ispositivecompletion (Reply)) {//Login to FTP server if (ftpclient.login (username, password)) {setfiletype (); 
} ftpclient.login (username, password); else {Ftpclient.discOnnect (); 
Logger.error ("FTP Service refuses connection!"); } catch (Exception e) {if (ftpclient.isconnected ()) {try {ftpclient.disconnect ();//Disconnect connection} catch (IOException E 
1) {Logger.error ("FTP Service disconnected failed!"); 
} logger.error ("FTP Service Connection failed!"); }/** * Set file Transfer type */private void Setfiletype () {try {if (binarytransfer) {Ftpclient.setfiletype (ftpclient.bin 
Ary_file_type); 
else {ftpclient.setfiletype (ftpclient.ascii_file_type); 
} catch (IOException e) {e.printstacktrace (); @Override public void Downloadremotefile (String filePath) {if Stringutils.endswith (FilePath, "/") | | 
Stringutils.endswith (FilePath, File.separator)) {FilePath = filepath.substring (0, Filepath.length ()-1); 
} File SaveFile = new file (FilePath); 
if (savefile.exists ()) {return; 
}//File directory String Path = filepath.substring (0, Filepath.lastindexof ("/")); if (! Stringutils.endswith (Path, "/") &&! Stringutils.endswith (path, file.separator)) {if (commander.islinux) {path = path + File. Separator; 
else {path = path + '/'; 
} outputstream output = null; 
try {//Create destination file path if (!savefile.getparentfile (). exists ()) {Savefile.getparentfile (). Mkdirs (); 
} savefile.createnewfile (); 
Transfer to FTP server directory ftpclient.changeworkingdirectory (path); 
Output = new FileOutputStream (savefile); 
Ftpclient.retrievefile (FilePath, Output); 
catch (IOException e) {logger.debug ("file:" + filePath + "______________________ download failed!"); 
E.printstacktrace (); 
finally {logger.debug ("file:" + filePath + "______________________ download successful!"); 
ioutils.closequietly (output); @Override public list<string> Listremotefilepath (String path) {list<string> List = new Arraylist<s 
Tring> (); try {if (! Stringutils.endswith (Path, "/") &&! 
Stringutils.endswith (path, file.separator)) {if (commander.islinux) {path = path + File.separator; 
else {path = path + '/'; 
} Boolean changedir = Ftpclient.changeworkingdirectory (path); if (changedir) {Ftpclient.setcontrolencoding (encoding); 
ftpfile[] files = ftpclient.listfiles (); 
for (Ftpfile file:files) {if (List.size () >= max) {break; } if (File.isdirectory ()) {if (! Stringutils.endswith (Path, "/") &&! 
Stringutils.endswith (path, file.separator)) {if (commander.islinux) {path = path + File.separator; 
else {path = path + '/'; 
} list.addall (This.listremotefilepath (path + file.getname ())); The else if (Changedir) {if (!) Stringutils.endswith (Path, "/") &&! 
Stringutils.endswith (path, file.separator)) {if (commander.islinux) {path = path + File.separator; 
else {path = path + '/'; 
} File savefile = new File (path + file.getname ()); 
if (!savefile.exists ()) {List.add (path + file.getname ()); 
catch (Exception e) {e.printstacktrace ()}}}} 
} return list; 
@Override public void CloseConnection () {if (ftpclient!= null) {try {ftpclient.logout (); 
catch (IOException e) {e.printstacktrace (); finally {if (Ftpclient.isconneCTED ()) {try {ftpclient.disconnect (); 
catch (IOException e) {e.printstacktrace (); 
}}}} [Java] view plain copy package com.eastrobot.remote; 
Import Java.io.File; 
Import Java.io.FileOutputStream; 
Import java.util.ArrayList; 
Import java.util.List; 
Import java.util.Properties; 
Import Java.util.Vector; 
Import Org.apache.commons.io.IOUtils; 
Import Org.apache.commons.lang.StringUtils; 
Import Org.apache.commons.logging.Log; 
Import Org.apache.commons.logging.LogFactory; 
Import Com.eastrobot.command.Commander; 
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 Filesftpremote extends Fileremote {protected session session = NULL; 
protected CHANNELSFTP channel = null; 
Private final static Log LOGGER = Logfactory.getlog (Filesftpremote.class); @OverriDe public void Initftpinfo (string host, string port, string Username, string password) {try {Jsch Jsch = new Jsch (); Create Jsch Object session = Jsch.getsession (username, host, Stringutils.isnotblank (port)? 
Integer.valueof (port): 22); Session.setpassword (password); 
Set Password Properties config = new properties (); 
Config.put ("stricthostkeychecking", "no"); Session.setconfig (config); Sets the properties Session.settimeout (60000) for the session object; Set timeout time session.connect (); Create links through session Channel Chan = Session.openchannel ("sftp"); Open the SFTP channel Chan.connect (); 
Establish the connection of the SFTP channel Channel = (CHANNELSFTP) Chan; 
catch (Exception e) {logger.error ("SFTP connection Failed"); 
E.printstacktrace (); @Override public void Downloadremotefile (String filePath) {if Stringutils.endswith (FilePath, "/") | | 
Stringutils.endswith (FilePath, File.separator)) {FilePath = filepath.substring (0, Filepath.length ()-1); 
} File SaveFile = new file (FilePath); 
FileOutputStream output = null; try {if (savefilE.exists ()) {return; 
///Create destination file path if (!savefile.getparentfile (). exists ()) {Savefile.getparentfile (). Mkdirs (); 
} savefile.createnewfile (); 
File directory String Path = filepath.substring (0, Filepath.lastindexof ("/")); if (! Stringutils.endswith (Path, "/") &&! 
Stringutils.endswith (path, file.separator)) {if (commander.islinux) {path = path + File.separator; 
else {path = path + '/'; 
} channel.cd (path); 
Channel.get (FilePath, New FileOutputStream (SaveFile)); 
Logger.debug ("File:" + filePath + "____________________________________________ download successful!"); 
catch (Exception e) {logger.debug ("file:" + filePath + "____________________________________________ download failed!"); 
E.printstacktrace (); 
Finally {ioutils.closequietly (output); @SuppressWarnings ("unchecked") @Override public list<string> Listremotefilepath (String path) {List<stri 
ng> list = new arraylist<string> (); 
Vector<lsentry> v = null; try {if (! Stringutils.endswith (Path, "/") && stringutils.endswith (path, file.separator)) {path = path + File.separator; 
} v = channel.ls (path); 
catch (Sftpexception e) {e.printstacktrace (); 
for (Lsentry lsentry:v) {if (List.size () >= max) {break; } if (!???). Equals (Lsentry.getfilename ()) &&! ". 
Equals (Lsentry.getfilename ())) {Sftpattrs attrs = Lsentry.getattrs (); if (Attrs.isdir ()) {if (! Stringutils.endswith (Path, "/") &&! 
Stringutils.endswith (path, file.separator)) {if (commander.islinux) {path = path + File.separator; 
else {path = path + '/'; 
} list.addall (This.listremotefilepath (path + lsentry.getfilename ())); } else {if (! Stringutils.endswith (Path, "/") &&! 
Stringutils.endswith (path, file.separator)) {if (commander.islinux) {path = path + File.separator; 
else {path = path + '/'; 
} File savefile = new File (path + lsentry.getfilename ()); 
if (!savefile.exists ()) {List.add (path + lsentry.getfilename ()); 
}} return list; 
}@Override public void CloseConnection () {try {if (channel!= null) {channel.quit (); 
Channel.disconnect (); 
} if (session!= null) {session.disconnect (); 
} catch (Exception e) {e.printstacktrace (); 
GetSession () {return session; 
} public void Setsession {this.session = session; 
Public Channelsftp Getchannel () {return channel; 
public void Setchannel (Channelsftp channel) {this.channel = channel; } 
}

The above is a small set to introduce the SFTP and FTP to the configuration of remote server address download files to the current service, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.