The relatively perfect FTP connection of Java upload files

xiaoxiao2021-03-06  59

This is even for the first time to write a Java program to realize the FTP data synchronization of the company, all the original code is as follows for all reference and valuable comments! In addition, there are two functions that have not been implemented. If you have a high-end pointing, how do you delete the files already downloaded on the FTP server? 2, how to change the uploaded file? When uploading, "TEMP_" is preceded before the file name. After the upload is completed, you need to change the file name. 3. How to use the openpassiveDataConnection () method to change the FTP connection to active connections, as you want to download files from the FTP server configured from UNIX system, you need to actively connect.

/ ************************************************** *********************************************************** *****

Filename: ftp.java author: Leetsing (Elove) Create Date: 2004-08-30 USE: Connect To FTP Server, THEN UPLOAD AND Download File Modify Date: 2004-09-05 Add to Upload File 2004-09-13 Add to To Download File Copy Right: Magisky Media Technology Co., Ltd.

*********************************************************** *********************************************************** **** /// Import cz.dhl.io. *; // Import cz.dhl.ftp. *; import sun.net.ftp. *; import sun.net. *; import java.applet. *; Import java.io. *; import java.io.ioException; import java.util.StringTokenizer; import sun.ftp.ftpclient; import java.util.ArrayList;

Public Class FTP EXTENDS Applet {FTPClient Aftp; DataOutputStream Outputs; TelnetInputStream INS; TelnetOutputStream Outs;

INTCCH; PUBLIC STRING A; String Hostname = ""; Private String Path = "/";

Public static void main (string "args) {string hostname =" 192.168.0.56 "; int port = 2121; string uid =" lee "; string pwd =" lee "; string rwfiledir =" D: // smsftp // ";//File Directory

/ / Connect the FTP server FTP ft = new ftp (); ft.connect (rwfiledir, hostname, port, uid, pwd);

// Download the file if (ft.aftp! = Null) {Try {ft.getnamelist (rwfiledir);} catch (ioException e) {system.out.println ("Download File error:" E);}}

// Upload file if (ft.aftp! = Null) {string sdir = rwfiledir "subunsubfromsp //"; file fdir = new file (sdir); string filename = ""; for (int i = 0; ifilename = SDIR) (fdir.list ()) [i];

ft.uploadfile (rwfiledir, filename);

}

//System.out.println ("Successfully Uploaded files:");

//ft.ShowFileContents ("subunsubfromsp// ");

}

/ / Delete the file file // ft.delefile (rwfiledir) that has been uploaded under the subunsubfromsp directory;

// Disconnect the server to connect ft.stop (rwfiledir);

}

Public ftpClient connect (String rwfiledir, string hostname, int port, string uid, string pwd) {this.hostname = hostname; system.out.println ("is connected" Hostname ", please wait .....") Try {AFTP = New fTPClient (Hostname, Port); Aftp.login (UID, PWD); Aftp.Binary (); //Aftp.OpenportDataConnection (); a = "Connection Host:" Hostname "success!"; System .out.println (a);} catch (ftPLoginexception e) {a = "login host:" hostname "failed! Please check if the username or password is correct:" E; system.out.println (a); / / RETURN FALSE;} Catch (IOException E) {a = "Connection Host:" Hostname "failed! Please check if the port is correct:" E; system.Out.println (a); // return false;} catch SecurityException E) {a = "No permissions and host:" hostname "connection! Please check if there is access:" E; system.out.println (a); // return false;} log (rwfiledir, a) Return Aftp;

Public void stoP (string rwfiledir) {string message = ""; try {if (AFTP! = null) {Aftp.closeServer (); message = "and host" hostname "connection is disconnected!"; System.out. Println; log (rwfiledir, message);}} catch (ioException e) {message = "and host" hostname "disconnected failed!" E; System.Out.Println (Message); log (rwfiledir , Message;}}

Public Boolean Downloadfile (String RwFiledir, String Filepathname) {Boolean Result = True; String Message = ""; if (AFTP! = NULL) {System.out.Println ("Download File" FilePathname ", please wait ... . "); String badfile = filepathname.substring (filepathname.length () - 4, filepathname.length ()); String badlog = filepathname.substring (filepathname.length () - 7, filepathname.length ()); String baddir = ""; (Badfile.comPareto (")! = 0) && (" Badlog.comPareto (". Badlog")! = 0)) {baddir = "subunsuBtosp //";} else {baddir = "Bad //";} string strdir = "subunsubtosp //"; //system.out.println (RWFiledir Baddir filepathname); try {// ftpclient fc = new ftpclient ("192.168.0.56", 2121); //fc.login("lee","lee "); int ch; File fi = new File (RWFileDir baddir filepathname); //aftp.cd(strdir); RandomAccessFile getFile = new RandomAccessFile (fi," rw "); Getfile.seek (0); telnetinputstream fget = Aftp.get (strdir filepathname); DataInputStream Puts = New DataInputStream (FGET); while ((chile)> = 0) {getfile.write ();} //s.delete (); fget.close (); getFile.close (); // Fc.closserver (); message = "Download" FilePathname "file to" Baddir "directory success!"; System.out.println (Message); log (rwfiledir, message);} catch (ioException e) {Message = "Download" FilePathname "file to" Baddir "directory failed!" E; System.Out.println (Message); log (rwfiledir, message); result = false;

}} Else {result = false;} return result;} public boolean uploadFile (String RWFileDir, String filepathname) {boolean result = true; String message = ""; if (! Aftp = null) {System.out.println ( " Upload file " filepathname ", please wait .... ");

try {String fg = new String ( "// subunsubfromsp //"); int index = filepathname.lastIndexOf (fg); String filename = filepathname.substring (index 1); File localFile = new File (filepathname); RandomAccessFile sendFile = New randomaccessfile (filepathname, "r"); // sendfile.seek (0); // Remove the name upload temp_ filename = filename.substring (0,15) "temp _" filename.substring (15, FileName.Length )); Outs = Aftp.put (filename); outputs = new dataputstream (outs); while (sendfile.getfilepointer ()

}} Else {result = false;} Return Result;

Public void rename (string newname) {//aftp.renameto(OldName ,NewName); file old = new file (oldName); // OldName File new = new file (newname); // newname // AFTP. Renameto (New); // Boolean Old.Renameto (file newname); //system.out.println (OLD); //system.out.println (new);} public static void delefile (String rwfiledir) {///// TRY {/ / TXT file STRING SDIR = RWFiledir "SUBUNSUBFROMSP / /"; file fdir = new file (sDIR); string filename = ""; int J = fdir.list (). Length; system. Number of files to be deleted under Out.println (SDIR "directory:" fdir.list (); length); file file; for (int i = 0; i

{

/ / Delete TXT files in SubunSubfromSP

Filename = rwfiledir "subunsubfromsp //" (fdir.list ()) [0];

FILE = New File (filename);

File.delete ();

System.out.println ("has successfully deleted" filename "file!"); ");

}

//}

// catch (ioexception e) {

// system.out.println ("Delete TXT file error!");

// E.PrintStackTrace ();

//}

}

Public void showfilecontents (string strdir) {stringbuffer buf = new stringbuffer (); try {offp.cd (strdir); ins = Aftp.list (); while ((ch = INS.READ ())> = 0) {BUF .append ((char) ch);} system.out.println (buf.tostring ());

INS.CLOSE ();} catch (ioexception e) {}}

/ / Return to all files and folders of the current directory

public ArrayList getFileList () throws IOException {BufferedReader dr = new BufferedReader (new InputStreamReader (aftp.list ())); ArrayList al = new ArrayList (); String s = ""; while ((s = dr.readLine ()) ! = null) {al.add (s);} return al;}

Public void setpath (String Path) throws ioException {if (AFTP == NULL) this.path = path; else {AFTP.CD (PATH);}} // Return to the file name of the current directory PUBLIC ArrayList GetNameList (String rwfileDir) Throws IOException {BufferedReader dr = new BufferedReader (new InputStreamReader (aftp.nameList ( "subunsubtosp //"))); ArrayList al = new ArrayList (); String s = ""; while ((s = dr.readLine ())! = null) {al.add (s); s = s.Substring (13, s.Length ()); isfile (s); Downloadfile (rwfiledir, s); // string strfiledelf = Aftp.namelist ("SubunSubtosp / / "); File Filedelf = New File (s); FileDelf.delete ();} return al; //system.out.println (it));}

/ / Judgment whether a line of file information is a directory

Public boolean isdir (string line) {return ((String) Parseline (line) .get (0)). INDEXOF ("D")! = -1;}

Public Boolean isfile (String line) {return! isdir (line);

/ / Handling the line information acquired by getFileList

Private arraylist parseline (string line) {ArrayList S1 = new arraylist (); stringtokenizer st = new stringtokenizer (line, ""); while (st.hasmoretoKens ()) {s1.add (st.nextToken ());} retturn S1;}

// Write message log public static void log (string rwfiledir, string msg) {string message = ""; try {java.text.dateformat DF = new java.text.SIMPLEDATEFORMAT ("YYYY-MM-DD HH: mm: SS "); Java.text.dateformat dflog = new java.text.SIMPLEDATEFORMAT (" YYYYMMDD "); java.util.date date = new java.util.date (); string datestr = DF.Format (new java.util." Date ()); string datelog = dflog.format (new java.util.date ()); // string datelog = datestr.substring (0, 10); // datelog = datelog.replace ('-', ') );

转载请注明原文地址:https://www.9cbs.com/read-114592.html

New Post(0)