English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dieser Artikel beschreibt, wie man die Apache-Toolscommons verwendet-Das von net bereitgestellte ftp-Tool ermöglicht das Hochladen und Herunterladen von Dateien auf den FTP-Server.
Eins, Vorbereitung
Es muss auf commons verwiesen werden-net-3.5.jar-Pakete.
Mithilfe von Maven importieren:
<dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.5</version> </dependency>
Manuelle Herunterladung:
https://de.oldtoolbag.com/softs/550085.html
Zwei, Verbinden Sie sich mit dem FTP Server
/** * Verbinden Sie sich mit dem FTP Server * @throws IOException */ public static final String ANONYMOUS_USER="anonymous"; private FTPClient connect(){ FTPClient client = new FTPClient(); try{ //Verbinden Sie sich mit dem FTP Server client.connect(this.host, this.port); //Anmeldung if(this.user==null||"".equals(this.user)){ //Anonyme Anmeldung verwenden client.login(ANONYMOUS_USER, ANONYMOUS_USER); } else{ client.login(this.user, this.password); } //Dateiformat einstellen client.setFileType(FTPClient.BINARY_FILE_TYPE); //Erhalten Sie die Antwort des FTP Servers int reply = client.getReplyCode(); if(!FTPReply.isPositiveCompletion(reply)){ client.disconnect(); return null; } //Wechseln Sie zum Arbeitsverzeichnis changeWorkingDirectory(client); System.out.println("===Mit FTP verbunden:")+host+: "+port); } catch(IOException e){ return null; } return client; } /** * Wechseln Sie zum Arbeitsverzeichnis, Verzeichnis wird erstellt, wenn das Remote-Verzeichnis nicht existiert * @param client * @throws IOException */ private void changeWorkingDirectory(FTPClient client) throws IOException{ if(this.ftpPath!=null&&!"".equals(this.ftpPath)){ Boolean ok = client.changeWorkingDirectory(this.ftpPath); if(!ok){ //ftpPath existiert nicht, Verzeichnis manuell erstellen StringTokenizer token = new StringTokenizer(this.ftpPath,"\\",//"); while(token.hasMoreTokens()){ String path = token.nextToken(); client.makeDirectory(path); client.changeWorkingDirectory(path); } } } } /** * FTP-Verbindung beenden * @param ftpClient * @throws IOException */ public void close(FTPClient ftpClient) throws IOException{ if(ftpClient!=null && ftpClient.isConnected()){ ftpClient.logout(); ftpClient.disconnect(); } System.out.println("!!!FTP-Verbindung beenden:")+host+: "+port); }
host: FTP-Server-IP-Adresse
port: FTP-Server-Port
user: Anmeldebenutzer
password: Anmeldepasswort
Wird der Anmeldebenutzer leer, wird der anonyme Benutzer verwendet.
ftpPath: FTP-Pfad, wird automatisch erstellt, wenn der FTP-Pfad nicht existiert. Bei mehrstufiger Verzeichnisstruktur müssen Verzeichnisse iterativ erstellt werden.
Drei. Datei hochladen
/** * Datei hochladen * @param targetName Dateiname auf FTP hochladen * @param localFile Pfad zur lokalen Datei * @return */ public Boolean upload(String targetName,String localFile){ //Verbindung mit ftp server FTPClient ftpClient = connect(); if(ftpClient==null){ System.out.println("Verbindung mit FTP-Server["+host+: "+port+"]fehler!"); return false; } File file = new File(localFile); //Dateiname nach dem Upload festlegen if(targetName==null||"".equals(targetName)) targetName = file.getName(); FileInputStream fis = null; try{ long now = System.currentTimeMillis(); //Upload der Datei beginnt fis = new FileInputStream(file); System.out.println(">>>Upload der Datei beginnt: "+); Boolean ok = ftpClient.storeFile(targetName, fis); if(ok){ //Upload erfolgreich long times = System.currentTimeMillis(); - now; System.out.println(String.format(">>>Upload erfolgreich: Größe:%s, Uploadzeit:%d Sekunden", formatSize(file.length()), times/1000)); } else//Upload fehlgeschlagen System.out.println(String.format(">>>Upload fehlgeschlagen: Größe:%s", formatSize(file.length()))); } catch(IOException e){ System.err.println(String.format(">>>Upload fehlgeschlagen: Größe:%s", formatSize(file.length()))); e.printStackTrace(); return false; } finally{ try{ if(fis!=null) fis.close(); close(ftpClient); } catch(Exception e){ } } return true; }
Vierter Abschnitt: Datei herunterladen
/** * Datei herunterladen * @param localPath Lokaler Speicherort * @return */ public int download(String localPath){ // Verbindung mit ftp server FTPClient ftpClient = connect(); if(ftpClient==null){ System.out.println("Verbindung mit FTP-Server["+host+: "+port+"]fehler!"); return 0; } File dir = new 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(new File(dir.getAbsolutePath()+File.separator+name)); System.out.println("<<<Beginne Dateidownload: "+name); long now = System.currentTimeMillis(); Boolean ok = ftpClient.retrieveFile(new String(name.getBytes("UTF-8"),"ISO-8859-1"), fos); if(ok){ //Download erfolgreich long times = System.currentTimeMillis(); - now; System.out.println(String.format("<<<Download erfolgreich: Größe:%s, Uploadzeit:%d Sekunden", formatSize(ftpFiles[i].getSize()), times/1000)); c++; } else{ System.out.println("<<<Download fehlgeschlagen"); } } catch(IOException e){ System.err.println("<<<Download fehlgeschlagen"); e.printStackTrace(); } finally{ try{ if(fos!=null) fos.close(); close(ftpClient); } catch(Exception e){ } } } return c; }
Formatiere die Dateigröße
private static final DecimalFormat DF = new DecimalFormat("#.##"); /** * Formatiere die Dateigröße (B, KB, MB, GB) * @param size * @return */ private String formatSize(long size){ " B";1024{ " KB"; + return size }1024*1024{ " KB";/1024 + else if(size< }1024*1024*1024{ return (size/(1024*1024)) + " MB"; }else{ double gb = size/(1024*1024*1024); return DF.format(gb)+" GB"; } }
5. 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/"); }
Result
=== Connected to FTP:192.168.1.10:21 >>> Start uploading file: TeamViewerPortable.rar >>> Upload successful: size:5 MB, upload time:3second !!! Disconnect FTP connection:192.168.1.10:21 === Connected to FTP:192.168.1.10:21 <<< Start downloading file: newFile.rar <<< Download successful: size:5 MB, upload time:4second !!! Disconnect FTP connection:192.168.1.10:21
Summary
This is the full content of the code explanation about implementing FTP file transfer using Apache tools in Java, I hope it will be helpful to everyone. Those who are interested can continue to read other related topics on this site, and welcome to leave a message if there are any shortcomings. Thank you for your support to this site!
Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)