In diesem Artikel wird hauptsächlich eingeführt, wie das FTP-Tool von Apache Toolset Commons-net verwendet wird, um Dateien auf den FTP-Server hochzuladen und herunterzuladen.
1. Vorbereitung
Müssen auf das Commons-Net-3.5.jar-Paket verweisen.
Importieren Sie mit Maven:
<Depopenty> <gruppe> commons-net </Groupid> <artifactId> commons-net </artifactId> <version> 3.5 </Version> </abhängig>
Handbuch Download:
//www.vevb.com/softs/550085.html
2. Verbindung zum FTP -Server herstellen
/** * Connect to FTP Server * @throws IOException */public static final String ANONYMOUS_USER="anonymous";private FTPClient connect(){FTPClient client = new FTPClient();try{//Connect FTP Serverclient.connect(this.host, this.port);//Login if (this.user == null || "". Equals (this.user)) {// login in client.login (anonymous_user, anonymous_user);} else {client.login (this.us.user recs.ser); Reply = client.getReplyCode (); if (! ftprepry.ispositiveCompletion (Antwort) {client.disconnect (); return null;} // Wechseln Sie das Arbeitsverzeichnis Änderung der Arbeitendirektorie (client); Client;}/*** Wechseln Sie das Arbeitsverzeichnis. Wenn das Remote -Verzeichnis nicht vorhanden ist, erstellen Sie das Verzeichnis * @param client * @throws ioException */private void changeworkingDirectory (ftpclient client) löscht ioException {if (this.ftppath! = Null &&! ". Client.ChangeWorkingDirectory (this.ftppath); if (! ok) {// ftppath existiert nicht, erstellen Sie das Verzeichnis manuell stringTokenizer token = new StringTokenizer (this.ftppath, "////"); while (token.hasmoretokens ()) {string path = path = token.nextToken();client.makeDirectory(path);client.changeWorkingDirectory(path);}}}}/** * Disconnect the FTP connection* @param ftpClient * @throws IOException */public void close(FTPClient ftpClient) throws IOException{if(ftpClient!=null && ftpclient.isconnected ()) {ftpclient.logout (); ftpclient.disconnect ();} System.out.println ("!!! disconnectftp Verbindung:"+host+":"+port);} Host: FTP Server IP -Adresse
Port: FTP Server -Port
Benutzer: Login -Benutzer
Kennwort: Wenn das Anmeldungskennwort leer ist, verwenden Sie einen anonymen Benutzer, um sich anzumelden.
FTPPATH: FTP -Pfad, automatisch erstellt, wenn der FTP -Pfad nicht existiert. Wenn es sich um eine mehrschichtige Verzeichnisstruktur handelt, muss das Verzeichnis iterativ erstellt werden.
3. Laden Sie Dateien hoch
/*** Datei hochladen* @param targetName hochladen auf ftp dateiname* @param localfile lokaler Dateipfad* @return*/public boolean upload (String targetName, String localFile) {// connect ftp serverftpclient ftpclient = connect (); if (ftpclient == null) {system.propintln ("Connect to (" Connect an ftpclient == null). server["+host+":"+port+"] failed!");return false;}File file = new File(localFile);//Set the file name after upload if(targetName==null||"".equals(targetName)) targetName = file.getName();FileInputStream fis = null;try{long now = System.currentTimeMillis();//Start upload file fis = new FileInputStream (Datei); System.out.println (">>> hochladen Datei:"+file.getName ()); boolean OK = ftpclient.storefile (targetName, fis); if (ok) {// load lobe langen tims %s, Upload -Zeit: %d Sekunden ", formatize (Datei.Length ()), Times/1000);} else // Upload fehlgeschlagenes System.out.println (string.format (" >>> Upload fehlgeschlagen: Größe: %s ", formatsize (Datei.Length ()); fehlgeschlagen: Größe: %s ", formatize (file.length ()))); e.printStacktrace (); return false;} schließlich {try {if (fis! = null) fis.close (); close (ftpclient);} catch (Ausnahme E) {}} return true;} true;} true;} true;} true;} true;} true;} true;} true;} true;} true;} true;} true;} true;} true;} true;} true;} true;} true;} true;} true;} true;} true;} true;} true;} true;} true;} true;} true;} true;} true;} true;4. Laden Sie die Datei herunter
/*** Datei herunterladen* @param LocalPath LocalPath Lokalspeicherpfad* @return*/public int download (String LocalPath) {// Connect zu ftp serverftpclient ftpclient = connect (); if (ftpclient == null) {System.out.Out.Println ("Connect to ftp Server ["+Host+":"+port+". File(localPath);if(!dir.exists()) dir.mkdirs();FTPFile[] ftpFiles = null;try{ftpFiles = ftpClient.listFiles();if(ftpFiles==null||ftpFiles.length==0) return 0;}catch(IOException e){return 0;}int c = 0;for (int i = 0; i <ftpfiles.length; i ++) {FileOutputStream fos = null; try {String name = ftpfiles [i] .getName (); fos = new FileOutputStream (neue Datei (Dir.Getabsolutepath ()+Datei. long now = system.currentTimemillis (); boolean ok = ftpclient.retrieveFile (neuer String (name.getBytes ("utf-8"), "iso-8859-1"), fos); if (ok) {// erfolgreich herunterladen. %s, Upload -Zeit: %d Sekunden ", Formatize (ftpfiles [i] .GetSize ()), Times/1000); Schließlich {try {if (fos!Formatdateigröße
private statische endgültige Dezimalformat df = new DecimalFormat ("#. ##"); / ** * Formatdateigröße (b, kb, mb, gb) * @param Größe * @return */ private String Formatize (lange Größe) {if (Größe <1024) {return size + "b"; } else if (Größe <1024*1024) {Return Size/1024 + "KB"; } else if (Größe <1024*1024*1024) {return (size/(1024*1024)) + "mb"; } else {double gb = size/(1024*1024*1024); return df.format (gb)+"gb"; }}V. Test
public static void main (String args []) {ftptest ftp = new ftptest ("192.168.1.10", 21, null, null, "/temp/2016/12"); ftp.upload ("newfile.rar", "d: /ftp/teamviewerPortable.rar"); System.out.println (""); ftp.download ("d:/ftp/"); }Ergebnis
=== Verbinden Sie eine Verbindung zu FTP: 192.168.1.10:21>>> Start -Upload -Datei: teamViewerPortable.RAR >>> erfolgreich hochgeladen: Größe: 5 MB, Upload -Zeit: 3 Sekunden !!! Abgenommene FTP -Verbindung: 192.168.1.10:21=. newfile.rar <<< erfolgreich entdeckt: Größe: 5 MB, Upload -Zeit: 4 Sekunden !!! getrennt FTP -Verbindung: 192.168.1.10:21
Zusammenfassen
Das obige ist die detaillierte Erläuterung der Verwendung von Apache Toolset durch Java zum Implementieren von FTP -Dateiübertragungscode. Ich hoffe, dass dies für alle hilfreich sein wird. Interessierte Freunde können weiterhin auf andere verwandte Themen auf dieser Website verweisen. Wenn es Mängel gibt, hinterlassen Sie bitte eine Nachricht, um darauf hinzuweisen. Vielen Dank an Freunde für Ihre Unterstützung für diese Seite!