Apache FTP는 널리 사용되는 FTP 업로드 클라이언트 도구입니다. 작동하기 쉽고 간단한 코드와 명확한 구조가 있습니다. FTP 파일 클라이언트 관리 소프트웨어의 우선 순위입니다. FTP 작업에는 다음이 포함됩니다. FTP 파일 업로드 (Breakpoint Continuous Transmission), FTP 파일 다운로드, FTP 파일 이름 변경 및 FTP 파일 삭제가 포함됩니다. 이러한 작업은 FTP 응용 프로그램 관리 방법을 완전히 입증했습니다. 그래서 저는 항상이 방법을 사용하여 FTP 파일 서버의 관리를 구현했습니다. FTP 도구 코드와 함께 첨부.
1. FTP 파일 작동 상태 열거 클래스
패키지 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_success (5), download_from_breaild (6), 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), not_exist_file (13), remote_rename_success (14), remote_rename_faild (15), file_not_unique (16); 개인 int 상태; public int getstatus () {return status; } public void setstatus (int status) {this.status = 상태; } ftpstatus (int status) {this.status = status; }} 2. FTP 파일 작동 도구 코드
패키지 com.scengine.wtms.utils.ftp; import java.io.file; import java.io.fileInputStream; import java.io.fileoutputStream; import java.io.ioexception; import java.io.inputstream; import java.io.outputStream; import java.io.outputStream; import java.io.printwriter; import javax.servlet.http.httpservletresponse; import org.apache.commons.net.printcommandlistener; import org.apache.commons.net.ftp.ftp; import org.apache.commons.net.ftp.ftpclient; import org.apache.commons.net.ftp.ftpfile; import org.apache.commons.net.ftp.ftpreply; import com.scengine.wtms.utils.log; 공개 클래스 ftputils {private ftpclient ftpclient = new ftpclient (); / *** 객체 구성 설정은 프로세스에 사용 된 명령을 콘솔에 출력*/ public ftputils () {this.ftpclient.addprotocolcommandListener (새 printCommandListener (new printWriter (System.out))); } / ** * * Java 프로그래밍에서 FTP 서버에 연결하는 데 사용되었습니다 * * @param hostname * hostname * * @param port * port * * @param username * * @param password * @return 연결이 성공적이든 * @throws ioexception * / public boolean connect (string hostname, string, string username, string username) ftpclient.connect (호스트 이름, 포트); if (ftpReply.ispositiveCepletion (ftpclient.getReplyCode ())) {if (ftpclient.login (username, password)) {return true; }} disternect (); 거짓을 반환합니다. } / ** * 원격 FTP 파일 삭제 * * @param remote * 원격 파일 경로 * @return * @Throws ioException * / public ftpstatus delete (String Remote)는 ioException {ftpclient.EnterLocalPassiveMode (); ftpclient.setfiletype (ftp.binary_file_type); ftpstatus result = null; ftpfile [] files = ftpclient.listfiles (원격); if (files.length == 1) {부울 상태 = ftpclient.deletefile (원격); 결과 = 상태? ftpstatus.delete_remote_success : ftpstatus.delete_remote_faild; } else {result = ftpstatus.not_exist_file; } log.getLogger (this.getClass ()). info ( "FTP 서버 파일 삭제 식별자 :"+result); 반환 결과; } / ** * 원격 FTP 파일의 이름을 바꾸십시오 * * @param 이름 * 새 원격 파일 이름 (Path-Must가 같은 경로 아래에 있음) * * @param 원격 파일 Path * * @return * * @throws ioexception * / public ftpstatus reme (문자열 원격) IoException {ftpclient.enterlocalprespivecode. ftpclient.setfiletype (ftp.binary_file_type); ftpstatus result = null; ftpfile [] files = ftpclient.listfiles (원격); if (files.length == 1) {부울 상태 = ftpclient.rename (원격, 이름); 결과 = 상태? ftpstatus.remote_rename_success : ftpstatus.remote_rename_faild; } else {result = ftpstatus.not_exist_file; } log.getLogger (this.getClass ()). info ( "FTP 서버 파일 이름 업데이트 식별자 :"+result); 반환 결과; } / ** * * ftp 서버에서 파일 다운로드 * * @param filename * 파일 이름 다운로드 (접미어 이름 포함) * * @param remote * 원격 파일 경로 * * @param local * local file path * * @return 성공 여부 * * @throws ioexception * / public ftpstatus 다운로드 (string filename, httpservletr responsk) {strowecceence replanse {httpservletrronce 응답) 팝업 파일 저장 경로 선택 창 응답 .setContentType ( "Application/Octet-stream"); response.setContentType ( "Application/Octet-stream; charset = utf-8"); response.setHeader ( "내용화", "첨부 파일; filename =" +filename); ftpclient.enterlocalPassiveMode (); ftpclient.setfiletype (ftp.binary_file_type); ftpstatus 결과; outputStream out = response.getOutputStream (); 부울 결과 = 상태? ftpstatus.download_from_break_success : ftpstatus.download_from_break_faild; log.getLogger (this.getClass ()). info ( "FTP 서버 파일 다운로드 식별자 :"+result); out.close (); 반환 결과; } / ** * ftp server에서 파일 다운로드 * * @param remote * 원격 파일 경로 * * @param local * local 파일 경로 * * @return 성공 여부 * * @throws ioexception * / @suppresswarnings ( "resource") public ftpstatus download (String remote, String local) dastrows ioexception {ftpclient.enterlocalpass (ftpclient); ftpclient.setfiletype (ftp.binary_file_type); ftpstatus 결과; 파일 f = 새 파일 (로컬); ftpfile [] files = ftpclient.listfiles (원격); if (files.length! = 1) {log.getLogger (this.getClass ()). info ( "원격 파일이 고유하지 않음"); ftpstatus.file_not_unique를 반환합니다. } long lremotesize = files [0] .getSize (); if (f.exists ()) {outputStream out = new FileOutputStream (f, true); log.getLogger (this.getClass ()). info ( "로컬 파일 크기는" + f.length ()); if (f.length ()> = lremotesize) {log.getLogger (this.getClass ()). 정보 ( "로컬 파일 크기는 원격 파일 크기보다 크다"); return ftpstatus.remote_smaller_local; } ftpclient.setRestArtOffSet (f.length ()); 부울 결과 = 상태? ftpstatus.download_from_break_success : ftpstatus.download_from_break_faild; out.close (); } else {outputStream out = new FileOutputStream (f); 부울 결과 = 상태? ftpstatus.download_from_break_success : ftpstatus.download_from_break_faild; out.close (); } 반환 결과; }/** * FTP 서버에 파일을 업로드하고 BreakPoint Continuous Transmission을 지원합니다 * @param local * 로컬 파일 이름, 절대 경로 * * @Param 원격 파일 경로 사용 /home/directory1/subdirectory/file.ext * Linux에 지정된 경로에 따르면 * * @Retsory의 재구성을 창출합니다. @Throws ioException */ @SuppressWarnings ( "Resource") public ftpstatus upload (문자열 로컬, 문자열 원격) IoException {// passiveMode를 ftpclient.enterlocalPassiveMode ()를 전송하기 위해 PassiveMode를 설정합니다. // ftpclient.setFileType (ftp.binary_file_type)를 전송하도록 설정; ftpstatus 결과; // 원격 디렉토리 처리 문자열 remoteFilename = 원격; if (remote.contains ( "/")) {remotefilename = remote.substring (remote.lastIndexof ( "/") + 1); 문자열 디렉토리 = remote.substring (0, remote.lastindexof ( "/") + 1); if (! directory.equalSeignoreCase ( "/") &&! ftpclient.changeworkingDirectory (directory)) {// 원격 디렉토리가 존재하지 않으면 원격 서버 디렉토리 int start = 0을 재귀 적으로 만듭니다. int end = 0; if (directory.startSwith ( "/"))) {start = 1; } else {start = 0; } end = directory.indexof ( "/", 시작); 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 ( "디렉토리 만들기 실패"); return ftpstatus.create_directory_fail; }} start = end + 1; end = directory.indexof ( "/", 시작); // 모든 디렉토리가 생성되었는지 확인하십시오 (END <= start) {break; }}}}} // remote ftpfile [] files = ftpclient.listfiles (remoteFilename)가 있는지 확인합니다. if (files.length == 1) {Long Remotesize = files [0] .getSize (); 파일 f = 새 파일 (로컬); 긴 현지 크기 = F.length (); if (remotesize == localalsize) {return ftpstatus.file_exits; } else if (remotesize> localsize) {return ftpstatus.remote_bigger_local; } // 파일의 포인터를 이동하여 중단 점 INPUTSTREAM의 중단이 = 새로운 FileInputStream (f); if (is.skip (remotesize) == remotesize) {ftpclient.setRestArtOffset (remotesize); if (ftpclient.storefile (remote, is)) {return ftpstatus.upload_from_break_success; }} // 중단 점이 계속해서 실패한 경우 서버에서 파일을 삭제하고 (! ftpclient.deletefile (remoteFilename)) {return ftpstatus.delete_remote_faild; } is = new FileInputStream (f); if (ftpclient.storefile (remote, is)) {result = ftpstatus.upload_new_file_success; } else {result = ftpstatus.upload_new_file_failed; } is.close (); } else {inputStream은 = new FileInputStream (local); if (ftpclient.storefile (remotefilename, is)) {result = ftpstatus.upload_new_file_success; } else {result = ftpstatus.upload_new_file_failed; } is.close (); } 반환 결과; } / ** * * 원격 서버에서 분리 * * @Throws ioException * / public void Disternect ()는 ioexception {if (ftpclient.isconnected ()) {ftpclient.disconnect (); }} public static void main (String [] args) {ftputils myftp = new ftputils (); try {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 ( "FTP 업로드 파일 예외 :" + e.getMessage ()); }}}위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.