About FTP upload files is not difficult, but sometimes face the reality of the environment is very painful, today I will share, ordinary upload file file to ftp way, it satisfies most of the FTP, but there are special, the next blog will be mentioned.
Below I use a ftputil, to achieve various functions:
Our main functions here are:
Upload the files under the local folder to one of the FTP folders, if the upload is successful, the upload successful files to another folder, if the backup is successful, you can take the backup successful file deleted.
Directly on the code!
Package Cn.tendency.utils;import Java.io.file;import Org.apache.commons.net.ftp.*;import Org.apache.log4j.Logger; Import Java.io.*;import Java.util.arraylist;public class Ftputil {private static Logger log = Logger.getlogger (ftputil.c LASS); Private ftpclient FTP; /** * File Upload FTP connection FTP server * @param URL * @param port * @param username * @param password * @param zippath * @param ftp Path * @param destpath */public void fileupl (string url, int port, string username, string password,string zippath, St Ring ftppath,string DestPath) {//Connect FTP Boolean SUCC =false; Boolean flag = false;try {succ = This.connect (Ftppath, URL, Port, username, password); Log.info ("Connect FTP" +SUCC);} catch (Exception e) {//TODO auto-generated catch Blocklog.error ("Connect FTP exception:" +e.getmessage ());} Switch directory//ftputil.changedirectory (FTP, Ftppath), if (SUCC) {log.info ("Connect FTP succeeded! Start uploading Files "); File File = new file (Zippath); try {flag=this.upload (file);} catch (Exception e) {//TODO auto-generated catch Blocklog.error ("Upload file exception:" +E.getmessage ()); E.printstacktrace ();} For the time being, note this line FTPUTIL.DISCONNECTFTP (FTP) first;} /*//after the upload successful backup compressed file, not successful can be passed the next time if (flag) {Boolean Flag1 = Filesutil.copyfile (Zippath, DestPath), if (FLAG1) {///backup deleted files after successful; Filesutil.deletedir (Zippath);}} Else{log.error ("Upload file failed! ");} */}/** * Create connection * @param URL * @param port * @param username * @param password * @return */public static ftpclient Conne Ctftp (string url, int port, string Username, string password) {//create FTP ftpclient FTP = NULL; try {//create address//inetaddress addr = new inetsocketaddress (URL, port); connect int reply; FTP = new FtpClient (); Ftp.connect (URL, port); Ftp.login (username, password); Ftp.setfiletype (Ftpclient.binary_file_type); Reply = Ftp.getreplycode (); if (! Ftpreply.ispositivecompletion (Reply)) {ftp.disconnect (); return FTP; } ftp.changeworkingdirectory ("/"); Landing//ftp.login (username, Password.tochararray ());//Ftp.login (username, password);// Ftp.changeworkingdirectory (path);//Ftp.setfiletype (Ftpclient.binary_file_type);//FTP.SETDA Tatimeout (6000);//Ftp.setconnecttimeout (6000); Ftp.setsotimeout (500000); } catch (Exception e) {e.printstacktrace (); } return FTP; }/** * * @param path is uploaded to the FTP server under which paths * @param addr Address * @param port port number * @pa RAM Username username * @param password Password * @return * @throws Exception */Private Boolean con Nect (String path,string addr,int port,string username,string password) throws Exception {Boolean result = FA Lse FTP = new FtpClient (); int reply; Ftp.connect (Addr,port); Ftp.login (Username,password); Ftp.setfiletype (ftpclient.bInary_file_type); Set the FTP connection timeout time//ftp.setdatatimeout (60000); Reply = Ftp.getreplycode (); if (! Ftpreply.ispositivecompletion (Reply)) {ftp.disconnect (); return result; } ftp.changeworkingdirectory (path); result = true; return result; }/** * Switch directory * @param FTP * @param path */public static void Changedirectory (FtpClient ftp, String Path) {try {//ftp.changedirectory (path); Ftp.changeworkingdirectory (path); } catch (Exception e) {e.printstacktrace (); }}/** * Close FTP * @param FTP */public static void Disconnectftp (FtpClient ftp) {try { Ftp.close (); Ftp.disconnect (); Log.info ("Disconnect success!!"); } catch (IOException e) {e.printstacktrace (); }}/** * Description: Uploading files to FTP server *@Version1.0 * @param URL FTP server hostname * @param port FTP server ports * @param username FTP login account * @param pass Word FTP Login Password * @param path FTP server to save directory * @param filename uploaded to FTP server file name * @param input stream * @return success Returns TRUE, otherwise false */public static Boolean UploadFile (String url,int port,string Username, string password, Strin G path, String filename, InputStream input) {Boolean success = false; ftpclient ftp = new FtpClient (); try {int reply; Ftp.connect (URL, port);//Connect FTP server//If you use the default port, you can connect directly to the FTP server using Ftp.connect (URL) ftp.login (usernam e, password);//Login reply = Ftp.getreplycode (); if (! Ftpreply.ispositivecompletion (Reply)) {ftp.disconnect (); return success; } ftp.changeworkingdirectory (path); Ftp.storefile (filename, input); Input.closE (); Ftp.logout (); Success = true; } catch (IOException e) {e.printstacktrace (); } finally {if (ftp.isconnected ()) {try {ftp.disconnect ()}; } catch (IOException IoE) {}}} return success; }/** * Upload file * @param localfile * @param ftpfile * @param FTP */public static Boolean U Pload_1 (String localfile, string ftpfile,ftpclient ftp,string url, int port, string Username, string password) {bo Olean flag = false; OutputStream OS = null; FileInputStream FIS = null; try {//To add the FTP file to the output stream. Output to ftp File File = new file (LocalFile); file[] file1 = File.listfiles (); if (null = = File1 | | file1.length<1) {log.error ("file directory to be uploaded:" + LocalFile + "There is no file inside."); }else{ Create a buffer for (int i=0;i<file1.length;i++) {//String str = ftpfile+ "/" +file1[i].getname (); Ftp.changeworkingdirectory ("/"); String str =file1[i].getname (); OS = Ftp.appendfilestream (str); if (OS = = null) {FTPUTIL.DISCONNECTFTP (FTP); ftp = ftputil.connectftp (URL, port, Username,password); Ftp.setfiletype (Ftpclient.binary_file_type); Ftp.setdatatimeout (6000); Ftp.setconnecttimeout (6000); OS = Ftp.appendfilestream (str); FIS = new FileInputStream (File1[i]); byte[] bytes = new BYTE[1024*10]; int C; while ((c = fis.read (bytes))! =-1) {os.write (bytes, 0, c); } os.flush (); Os.close (); Fis.close ();//Ftp1.disconnect (); } flag = true; Log.info ("Upload success!!"); }} catch (Exception e) {e.printstacktrace (); } finally {try {if (os!=null) {os.close (); } if (Fis!=null) {fis.close (); }} catch (IOException e) {e.printstacktrace (); }} return flag; }/** * * @param file or folder uploaded by file * @throws Exception */Private Boolean Uplo AD (file file) throws exception{Boolean flag=false; arraylist<integer> numlist = new arraylist<integer> (); int a=0; try {if (File.isdirectory ()) {///We are reading the directory Log.info ("uploaded folder"); Ftp.makedirectory (File.getname ()); Ftp.changeworkingdirectory (File.getname ()); string[] files = file.list (); Number of files int filenum=files.length; Log.info ("+filenum+" File under "folder"); if (filenum>4) {filenum=4; } for (int i = 0; i < FileNum; i++) {File File1 = new File (File.getpath () + "\ \" +files[i ] ); if (File1.isdirectory ()) {upload (file1); Ftp.changetoparentdirectory (); }else{//execute this file File2 = new file (File.getpath () + "\ \" +files[i]); FileInputStream input = new FileInputStream (file2); Ftp.enterlocalpassivemode (); Ftp.storefile (File2.getname (), input); Log.info ("Upload file" +file.getpath () + "\ \" +files[i]+ "success"); Input.close (); flag=true;// After uploading a successful backup of the compressed file, the next time can be passed if (flag) {//backup Boolean Flag1 = Filesutil.copyfile2 (file2, "d:\\maccollect\\l Aibin_maccollect\\maccollect\\laibin\\zip_backup "); if (FLAG1) {//delete files after successful backup; File2.delete (); }else {log.error ("Backup file failed! ");} } else{log.error ("Upload file failed! "); }}}}else{//This item does not go this one file File2 = new file (file.g Etpath ()); FileInputStream input = new FileInputStream (file2); Ftp.enterlocalpassivemode (); Ftp.storefile (File2.getname (), input); Input.close (); Flag=true; }} catch (Exception e) {flag=false;log.error ("Upload file exception:" +e.getmessage ()); E.printstacktrace ();} return flag; }}
Here is the code for the file backup:
In two cases: the first is to back up all folders under one directory to another directory
The second is to back up a single file to another directory
First is the first case:
/* * Copy files back to the corresponding date directory, referencing the Xmlcopyfile method; */public Static Boolean CopyFile (String srcfilename, String destfilename) {Boolean flag = false; File Srcfile = new file (srcfilename);//Determine if the source file exists if (!srcfile.exists ()) {log.error ("source file:" + Srcfilename + "does not exist!) "); return flag;} else if (!srcfile.isdirectory ()) {Log.error ("copy failed, source file:" + Srcfilename + "is not a path!) "); return flag;} file[] Bfile = Srcfile.listfiles (); Flag = Filesutil.xmlcopyfile (destFileName, Bfile); return flag;} public static Boolean Xmlcopyfile (String destfilename, file[] Bfile) {//File Srcfile = new file (srcfilename);////Determine source file is No presence//if (!srcfile.exists ()) {//Log.error ("source file:" + Srcfilename + "does not exist!) ");//Return false;//} else if (!srcfile.isdirectory ()) {//Log.error (" Copy failed, source file: "+ Srcfilename +" is not a path!) ");//return false;//}//String month=destfilename = destfilename + filesutil.getformatdate (); Log.info (" Backup path: "+destfil ENAME);//Determine if the target file exists with the files DestFile = new file (destfilename); if (!destfile.exists ()) {try {Boolean flag = Destfile.mkDirs (); Log.info ("True or false:" + flag); catch (Exception e) {e.printstacktrace ();}} Copy file int byteread = 0; Number of bytes read InputStream in = Null;outputstream out = null;try {if (null = = Bfile | | Bfile.length < 1) {Log.error (file not found in file directory to be copied);} else {for (int i = 0; i < bfile.length; i++) {in = new fileinputs Tream (Bfile[i]); out = new FileOutputStream (destFileName + "/" + bfile[i].getname ()); byte[] buffer = new Byte[1024];while ( (Byteread = in.read (buffer))! =-1) {out.write (buffer, 0, byteread);} Out.close (); In.close ();}} Log.info ("Backup success!"); return true;} catch (FileNotFoundException e) {return false;} catch (IOException e) {return false;} finally {try {if (out! = null) out.cl OSE (); if (in! = null) In.close ();} catch (IOException e) {e.printstacktrace ();}}}
Second case:
/** The above method modification * Copy file backup to the corresponding date directory, referring to the XmlCopyFile2 method; */ Public Static BooleanCopyFile2 (File srcfile, String destfilename) {BooleanFlag =false; //determine if the source file exists if(!srcfile.exists ()) {Log.error ("Source file:" + srcfile + "does not exist! "); returnFlag; } Flag=filesutil.xmlcopyfile2 (destFileName, srcfile); returnFlag; } Public Static BooleanXmlCopyFile2 (String destfilename, File Bfile) {destfilename= destFileName +filesutil.getformatdate (); Log.info ("Backup path:" +destfilename); //determine if the target file existsFile DestFile =NewFile (destFileName); if(!destfile.exists ()) { Try { BooleanFlag =Destfile.mkdirs (); Log.info ("True or false:" +flag); } Catch(Exception e) {e.printstacktrace (); } } //Copying Files intByteread = 0;//number of bytes readInputStream in =NULL; OutputStream out=NULL; Try{ in=NewFileInputStream (Bfile); out=NewFileOutputStream (destFileName + "/" +bfile.getname ()); byte[] buffer =New byte[1024]; while((Byteread = in.read (buffer))! =-1) {out.write (buffer,0, Byteread); } out.close (); In.close (); Log.info ("Backup Success!"); return true; } Catch(FileNotFoundException e) {return false; } Catch(IOException e) {return false; } finally { Try { if(Out! =NULL) Out.close (); if(In! =NULL) In.close (); } Catch(IOException e) {e.printstacktrace (); } } }
OK, the above is the normal way to upload ftp and backup files.
File upload for normal Java FTP client