Un proyecto que solía hacer en el pasado, cargando archivos al servidor FTP, y ahora lo reviso. Es relativamente simple y puedes entenderlo de una vez.
Entorno: primero, instale primero el servidor FTP. Lo configuré localmente en Win8 con IIS. Puede encontrar el documento de instalación en Baidu.
1. Cree un archivo de configuración FTP en su directorio de proyecto, el directorio es como se muestra a continuación
01 ftpconfig.properties:
FTPIP = 10.73.222.29
ftpport = 21
ftpuser = wp
ftppwd = 04143114WP
ftpremotepath = d: // compartir
02 clase que lee el contenido específico en ftpconfig.properties:
paquete com.java.core.util; import java.io.ioexception; import java.io.inputstream; import java.util.properties;/*** @author wangpei* @version creado: 6 de mayo de 2017 a las 9:42:40 PM PM Lea el archivo de configuración del archivo FTP*/Public Classionproperties {privado de entrada { Propiedades de propiedades privadas; public readftpRoperties () {is = this.getClass (). getResourceasstream ("/ftpconfig.properties"); // lea el archivo de configuración en las propiedades de flujo de entrada = new Properties (); Pruebe {Properties.load (is); } catch (ioException e) {System.out.println ("El archivo de configuración no existe ..."); E.PrintStackTrace (); } finalmente {if (null! = is) {try {is.close (); } catch (ioException e) {System.out.println ("Fallado de flujo cerrado ..."); E.PrintStackTrace (); }}}} public String getip () {// Obtener las propiedades de retorno de la dirección IP del servidor FTP.getProperty ("ftpip"); } public String getPort () {// Obtener el puerto de las propiedades de retorno del servidor FTP.getProperty ("ftpport"); } public String getUser () {// Obtener el nombre de usuario FTP de usuario de usuario de usuario. } public String getPwd () {// Obtenga la contraseña de inicio de sesión de las propiedades de retorno del servidor FTP.getProperty ("ftppwd"); } public String getRemotePath () {// Obtenga el directorio donde los archivos se almacenan en el servidor FTP se devuelven propiedades.getProperty ("ftpremotePath"); }}03 La clase de interfaz para la carga y descarga de archivos
paquete com.java.web.service; import java.io.inputstream; importar org.apache.commons.net.ftp.ftpclient; import com.java.core.util.readftpproperties;/** * @author wangpei * @version creado: 6 de mayo de 2017 a las 6:39:03 pm * Archivo uplado de archivo interfaz ftpservice { / * * Iniciar sesión en ftp * / public boolean loginftp (cliente ftpClient, readftproperties rfp); / * * Soge de FTP */ Public Boolean logrout (cliente ftpClient); /// * * cargue el archivo en remottePath, cuyo nombre en ftp es inputStream */ public boolean uploadfile (ftpClient Client, string remotePath, string fileneWnam, inputStream inputam, readftpLoperties rfp); / * * Descargue el nombre de archivo del archivo desde el directorio remotePath */ public inputStream downfileByftp (cliente ftpClient, string remotePath, string fileName); /** Eliminar el archivo con el nombre de ruta del directorio en ftp*/ public boolean delfile (cliente ftpClient, string pathname);}04 La clase de implementación de interfaz para la carga y descarga de archivos
paquete com.java.web.service.serviceImpl; import java.io.ioException; import java.io.inputstream; import java.io.unsupportedencodingexception; import java.net.socketexception; importar org.apache.comtp.ftp.ftp; org.apache.commons.net.ftp.ftpfile; import com.java.core.util.readftpproperties; import com.java.web.service.ftpservice;/*** @author wangpei* @version creó tiempo: 6 de mayo de 2017 a las 10:02:28 PM Class Descripción*/Public Class FtpSerViceMaplements boolean loginftp (cliente ftpClient, readftpProperties rfp) {string ftpip = rfp.getip (); Cadena ftpport = rfp.getport (); Cadena ftpuser = rfp.getuser (); Cadena ftppwd = rfp.getpwd (); // cadena fgtpremotePath = rfp.getRemotePath (); booleano b = falso; intente {client.connect (ftpip, integer.parseInt (ftpport)); } catch (numberFormateException e) {System.out.println ("no se puede conectar a ftp"); devolver falso; } catch (SocketException e) {System.out.println ("no se puede conectar a ftp"); devolver falso; } catch (ioException e) {System.out.println ("no se puede conectar a ftp"); devolver falso; } catch (ioException e) {System.out.println ("no se puede conectar a ftp"); devolver falso; } client.setControlEncoding ("Uft-8"); intente {b = client.login (ftpuser, ftppwd); } catch (ioException e) {System.out.println ("Error de sesión ftp de inicio"); logrout (cliente); // logrout/disconnect FTP Server Link return false; } retorno b; } Public boolean logrout (cliente ftpClient) {boolean b = false; Pruebe {b = client.logout (); // logrout client.disconnect (); // disconnect} catch (ioException e) {return false; } retorno b; } public boolean uploadFile (ftpClient Client, string remotePath, string fileNeWName, inputStream inputStream, readftpRoperties rfp) {boolean b = false; intente {Client.setFileType (ftpclient.binary_file_type); Client.ENTERLOCALPASSIVEMODE (); if (remotePath! = null &&! "". Equals (remotePath.trim ())) {string [] rutas = remotePath.split ("/"); for (String OnePath: Paths) {if (OnePath == NULL || "" .Equals (OnePath.trim ())) {continuar; } onePath = new String (OnePath.getBytes ("UTF-8"), "ISO-8859-1"); System.out.println ("OnePath =" + OnePath); if (! Client.changeWorkingDirectory (OnePath)) {Client.MakedIrectory (OnePath); // Cree un directorio de servidor FTP Client.ChangeWorkingDirectory (OnePath); // Cambie el directorio de servidores FTP} else {System.out.println ("File Single Rath"); }}} b = Client.storeFile (new String (FileNeWname.getBytes ("UTF-8"), "ISO-8859-1"), inputStream); } catch (UnsupportedEncodingException e) {return false; } catch (ioException e) {return false; } retorno b; } public inputStream downfileByftp (ftpClient ftpClient, string remotePath, string fileName) {ftpfile [] fs; InputStream es = nulo; intente {// establecer el modo pasivo ftpclient.enterLocalPassivEmode (); // establecer ftpclient.setFileType (ftp.binary_file_type); // establecer formato de edición ftpclient.setControlEncoding ("UTF-8"); remotePath = remotePath.substring (0, remotePath.lastIndexOf (nombre de archivo)); fs = ftpClient.listFiles(remotePath);// Recursive target directory for (FTPFile ff : fs) { if (ff.getName().equals(fileName)) {// Find the target file is = ftpClient.retrieveFileStream(new String( (remotePath + fileName).getBytes("utf-8"), "ISO-8859-1")); romper; }}} Catch (ioException e) {E.PrintStackTrace (); } retorno es; } public boolean Delfile (ftpClient ftpClient, string pathname) {boolean b = false; intente {b = ftpclient.deleteFile (rathName); regreso B; } capt (excepción e) {return false; } Finalmente {logrout (ftpClient); // salir/desconectar el enlace del servidor FTP}}}El código es fácil de entender, debe entenderse leyéndolo una vez. No lo analizaré específicamente aquí, principalmente mira los comentarios en el código.
Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.