O Apache FTP é uma ferramenta de cliente de upload FTP amplamente usada. É fácil de operar, possui código simples e estrutura clara. É uma prioridade para o software de gerenciamento de clientes de arquivo FTP. As operações do FTP incluem: Upload de arquivo FTP (transmissão contínua do ponto de interrupção), download do arquivo FTP, renomeação de arquivos FTP e exclusão de arquivo FTP. Essas operações demonstraram totalmente o método de gerenciamento de aplicativos FTP. Por isso, sempre usei esse método para implementar o gerenciamento de servidores de arquivos FTP; anexado ao código da ferramenta FTP.
1. Classe de enumeração de operação do arquivo FTP
pacote com.scengine.wtms.utils.ftp; public enum ftpstatus {file_exits (0), create_directory_success (1), create_directory_fail (2), upload_from_break_success (3), upload_from_break_faild (4), download_from_break_sucs (5), download_from_frunse_fraild_faild (4), download_frombreak_suct (5). Upload_new_file_success (7), upload_new_file_failed (8), delete_remote_success (9), Delete_remote_faild (10), remote_bigger_local (11), remote_smaller_local (12), não_exist_file (13), remote_rename_success (14), remote_rename_faild (15), file_not_unique (16); status privado int; public int getStatus () {retornar status; } public void setStatus (status int) {this.status = status; } Ftpstatus (status int) {this.status = status; }} 2. Código da ferramenta de operação de arquivo FTP
pacote com.scengine.wtms.utils.ftp; importar java.io.file; importar java.io.fileInputStream; importar java.io.fileOutputStream; importar java.io.ioException; importar java.io.inputStream; importar java.io.OutputStream; importar java.io.OutputStream; importar java.io.printwriter; importar javax.servlet.http.httpServletResponse; importar org.apache.commons.net.printCommandListener; importar org.apache.commons.net.ftp.ftp; importar org.apache.commons.net.ftp.ftpClient; importar org.apache.commons.net.ftp.ftpfile; importar org.apache.commons.net.ftp.ftpreply; importação com.scengine.wtms.utils.log; classe pública ftputils {private ftpClient ftpClient = new ftpClient (); / *** Configurações de construção do objeto Saída Os comandos usados no processo para o console*/ public ftputils () {this.ftpclient.addprotocolCommandListener (novo printCommandListener (new PrintWriter (System.out))); } /** * * Used to connect to the FTP server in java programming* * @param hostname * Hostname * * @param port * Port * * @param username * Username * * @param password * Password * @return Whether the connection is successful* * @throws IOException */ public boolean connect(String hostname, int port, String username, String password) throws IOException { ftpClient.Connect (nome do host, porta); if (ftPreply.ispositiveciction (ftpClient.getReplyCode ())) {if (ftpClient.login (nome de usuário, senha)) {return true; }} desconect (); retornar falso; } / ** * Exclua arquivo FTP remoto * * @param remoto * caminho do arquivo remoto * @return * @throws ioexception * / public ftpstatus delete (string remoto) lança ioexception {ftpclient.enterlocalPassivEmode (); ftpClient.SetFileType (ftp.binary_file_type); Resultado ftpstatus = nulo; Ftpfile [] arquivos = ftpclient.listfiles (remoto); if (files.length == 1) {status booleano = ftpClient.DeleteFile (remoto); resultado = status? Ftpstatus.delete_remote_success: ftpstatus.delete_remote_faild; } else {resultado = ftpstatus.not_exist_file; } Log.getLogger (this.getClass ()). Info ("Identificador de exclusão do arquivo do servidor FTP:"+resultado); resultado de retorno; } / ** * Renomeie o arquivo FTP remoto * * Nome @param * Novo nome do arquivo remoto (Path-Must deve estar no mesmo caminho) * * @param remoto * caminho de arquivo remoto * * @return se é bem-sucedido * * @THOXCIPCECCIONCECCECTIONS * / public ftpStatus Rename (string name, string remote) ftpClient.SetFileType (ftp.binary_file_type); Resultado ftpstatus = nulo; Ftpfile [] arquivos = ftpclient.listfiles (remoto); if (files.length == 1) {status booleano = ftpclient.rename (remoto, nome); resultado = status? Ftpstatus.remote_rename_success: ftpstatus.remote_rename_faild; } else {resultado = ftpstatus.not_exist_file; } Log.getLogger (this.getClass ()). Info ("FTP Server FileName Atualize Identificador:"+resultado); resultado de retorno; } / ** * * Download Arquivo do servidor FTP * * @Param FileName * Download Nome do arquivo (incluindo nome do sufixo) * * @param remoto * caminho do arquivo remoto * * @param local * caminho de arquivo local * * @return sell @@ThThows IoException * / public ftpStatus Download (string fileName, strings Remote, ht ht ht ht ht (ht) / public ftpStatus Download (string fileName, string Remote, ht ht ht ht ht * / public ftpStatus Download (string -fillename, string Remote, ht ht ht ht ht * / public ftpStatus Download (string filename, string RemoT Pop-up Salvar a janela de seleção do caminho Resposta.SetContentType ("Application/Octet-Stream"); Response.setContentType ("Application/Octet-Stream; Charset = UTF-8"); Response.setheader ("Content-Disposition", "Applement; FileName =" +FileName); ftpClient.enterlocalPassivEMode (); ftpClient.SetFileType (ftp.binary_file_type); Resultado ftpstatus; OutputStream out = Response.getOutputStream (); status booleano = ftpClient.retrievefile (remoto, out); resultado = status? ftpstatus.download_from_break_success: ftpstatus.download_from_break_faild; Log.getLogger (this.getClass ()). Info ("Identificador de download do arquivo de arquivo do servidor FTP:"+resultado); out.Close (); resultado de retorno; } / ** * Faça o download do arquivo do servidor ftp * * @param remoto * caminho do arquivo remoto * * @param local * caminho do arquivo local * * @return se é bem -sucedido * * @throws ioexception * / @suppresswarnings ("resource") public ftpstatus download (string remote, string local) throwsemoException {FinPenting; ftpClient.SetFileType (ftp.binary_file_type); Resultado ftpstatus; Arquivo f = novo arquivo (local); Ftpfile [] arquivos = ftpclient.listfiles (remoto); if (files.length! = 1) {log.getLogger (this.getclass ()). info ("arquivo remoto não é exclusivo"); return ftpstatus.file_not_unique; } long lremotesize = arquivos [0] .getSize (); if (f.Exists ()) {outputStream out = new FileOutputStream (f, true); Log.getLogger (this.getClass ()). Info ("O tamanho do arquivo local é:" + f.Length ()); if (f.Length ()> = lremotesize) {Log.getLogger (this.getClass ()). Info ("O tamanho do arquivo local é maior que o tamanho do arquivo remoto, download abortado"); return ftpstatus.remote_smaller_local; } ftpClient.SetRestarToffset (f.Length ()); status booleano = ftpClient.retrievefile (remoto, out); resultado = status? ftpstatus.download_from_break_success: ftpstatus.download_from_break_faild; out.Close (); } else {outputStream out = new FileOutputStream (f); status booleano = ftpClient.retrievefile (remoto, out); resultado = status? ftpstatus.download_from_break_success: ftpstatus.download_from_break_faild; out.Close (); } resultado de retorno; }/** * Faça o upload do arquivo para o servidor FTP, suporta transmissão contínua do ponto de interrupção * * @param local * Nome do arquivo local, caminho absoluto * * @param remoto * caminho de arquivo remoto, use /home/directory1/subdirectory/file.ext * de acordo com o caminho especificado no linux, o ninho do linux, o ninho do nível do linux, o ninho do nível do linux, não é o que é o que não é o relatório do linux, o ninho do linux, e o Recurntorning é o caminho do linux. @THOWSoException */ @suppresswarnings ("Resource") public ftpStatus upload (string local, string remoto) lança ioexception {// define passivemode para transmitir ftpclient.enterlocalpassivemode (); // Defina como transmitir ftpclient.setFileType (ftp.binary_file_type); Resultado ftpstatus; // processamento de diretórios remotos string remotefilename = remoto; if (remote.contains ("/")) {remotefilename = remote.substring (remote.lastindexof ("/") + 1); String diretório = remote.substring (0, remote.lastIndexOf ("/") + 1); if (! diretório.equalsignorecase ("/") &&! ftpclient.ChangeWorkingDirectory (diretório)) {// Se o diretório remoto não existir, crie recursivamente o diretório de servidor remoto int start = 0; int end = 0; if (diretório.startswith ("/"))) {start = 1; } else {start = 0; } end = Directory.indexof ("/", Start); while (true) {String subdirectory = remote.substring (start, end); if (! ftpClient.ChangeWorkingDirectory (subdirectory)) {if (ftpClient.Makedirectory (Subdirectory)) {ftpClient.ChangeWorkingDirectory (subdirectory); } else {log.getLogger (this.getclass ()). info ("Criar diretório falhado"); return ftpstatus.create_directory_fail; }} start = end + 1; end = diretório.indexof ("/", start); // Verifique se todos os diretórios foram criados se (end <= start) {break; }}}}} // Verifique se há um arquivo remoto ftpfile [] arquivos = ftpclient.listfiles (remotefileName); if (files.Length == 1) {Long Remotesize = arquivos [0] .getSize (); Arquivo f = novo arquivo (local); Long Localsize = F.Length (); if (remoTesize == Localsize) {return ftpstatus.file_exits; } else if (remotosize> localsize) {return ftpstatus.remote_bigger_local; } // Tente mover o ponteiro no arquivo para realizar a interrupção do ponto de interrupção inputStream is = new FileInputStream (f); if (is.skip (remotaSize) == remotorsize) {ftpclient.setRestartOffset (remotorsize); if (ftpClient.storefile (remoto, is)) {return ftpstatus.upload_from_break_success; }} // Se o ponto de interrupção continuar passando sem sucesso, exclua o arquivo no servidor e o envie novamente se (! } is = new FileInputStream (f); if (ftpClient.storeFile (remoto, is)) {resultado = ftpstatus.upload_new_file_success; } else {resultado = ftpstatus.upload_new_file_failed; } is.close (); } else {inputStream is = new FileInputStream (local); if (ftpClient.StoreFile (RemoteFileName, is)) {resultado = ftpstatus.upload_new_file_success; } else {resultado = ftpstatus.upload_new_file_failed; } is.close (); } resultado de retorno; } / ** * * Desconecte do servidor remoto * * @THOWSowsoException * / public void desconect () lança ioexception {if (ftpclient.isconnected ()) {ftpclient.disconnect (); }} public static void main (string [] args) {ftputils myftp = new ftputils (); tente {myftp.connect ("192.168.1.200", 21, "Duser", "htpduserxp32"); Log.getLogger (ftputils.class) .info (myftp.upload ("c: //users//administrator//desktop//swing.drawer.jar", "/jars/swing.drawer.jar"); myftp.disconnect (); } catch (ioexception e) {log.getLogger (ftputils.class) .info ("Exceção do arquivo de upload FTP:" + e.getMessage ()); }}}O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.