Apache FTP를 기반으로 파일을 업로드 할 때 다음과 같은 문제를 고려해야합니다 (예제는 연속 기능입니다).
(1) FTP 서버에 디렉토리 변경이 있는지 여부, 존재하지 않는 경우 디렉토리를 만들어야합니다.
(2) 업로드 된 파일이 이미 존재하는지 확인하십시오. 존재하는 경우 업로드되거나 계속 전송되기 전에 삭제해야합니다.
1. 열거 클래스 업로드 또는 다운로드 :
패키지 com.scengine.wtms.utils.ftp; public enum uploadstatus {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_locall (12); 개인 int 상태; public int getstatus () {return status; } public void setstatus (int status) {this.status = 상태; } uploadstatus (int status) {this.status = status; }}2. 도구 코드 :
패키지 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.printwriter; 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; 공개 클래스 계속 FTPCLIENT FTPCLIENT = NEW FTPCLIENT (); / *** 객체 구성 설정은 프로세스에 사용 된 명령을 콘솔에 출력*/ public wondistp () {this.ftpclient.addprotocolcommandListener (new PrintCommandListener (new PrintWriter (System.out))); } / ** * * Java 프로그래밍에서 FTP 서버에 연결하는 데 사용 * * @param hostname * hostname * @param port * @param username * username * @param password * password * @return 연결이 성공적이든 * @throws ioexception * / public boolean connect (문자열 hostname, int port, strows) ftpclient.connect (호스트 이름, 포트); if (ftpReply.ispositiveCepletion (ftpclient.getReplyCode ())) {if (ftpclient.login (username, password)) {return true; }} disternect (); 거짓을 반환합니다. } / ** * * ftp 서버에서 파일 다운로드 * * @param remote * 원격 파일 경로 * * @param local * 로컬 파일 경로 * * @return * * @throws ioexception * / @suppresswarnings ( "resource") public boolean download (String remote, String local) Ioexception {ftpclient.enterlocal Passe (ftpclient.enterlocal Passe); ftpclient.setfiletype (ftp.binary_file_type); 부울 결과; 파일 f = 새 파일 (로컬); ftpfile [] files = ftpclient.listfiles (원격); if (files.length! = 1) {System.out.println ( "원격 파일이 고유하지 않음"); 거짓을 반환합니다. } long lremotesize = files [0] .getSize (); if (f.exists ()) {outputStream out = new FileOutputStream (f, true); System.out.println ( "로컬 파일 크기는" + f.length ()); if (f.length ()> = lremotesize) {System.out.println ( "로컬 파일 크기는 원격 파일 크기보다 크고 다운로드 중단"); 거짓을 반환합니다. } ftpclient.setRestArtOffSet (f.length ()); 결과 = ftpclient.retrivefile (원격, 출력); out.close (); } else {outputStream out = new FileOutputStream (f); 결과 = ftpclient.retrivefile (원격, 출력); out.close (); } 반환 결과; }/** * * FTP 서버에 파일을 업로드하고 BreakPoint Continuous Transmission을 지원합니다 * @param local * 로컬 파일 이름, 절대 경로 * * @Param 원격 파일 경로, /home/directory1/subdirectory/file.ext *를 Linux에 지정한 경로에 따라 * @retrone * @Retural Spructures를 지원합니다. @Throws ioException */ @SuppressWarnings ( "Resource") public uploadstatus upload (문자열 로컬, 스트링 remote)는 ioexception {// passiveMode를 ftpclient.enterlocalPassiveMode ()를 전송하기 위해 PassiveMode를 설정합니다. // set ftpclient.setFileType (ftp.binary_file_type); 업로드 스태투스 결과; // 원격 디렉토리 처리 문자열 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 {system.out.println ( "디렉토리를 만들지 못했습니다"); uploadstatus.create_directory_fail을 retuck; }} start = end + 1; end = directory.indexof ( "/", 시작); // 모든 디렉토리가 생성되었는지 확인하십시오 (END <= start) {break; }}}} // 파일이 원격 ftpfile [] files = ftpclient.listfiles (remoteFilename)에 존재하는지 확인합니다. if (files.length == 1) {Long Remotesize = files [0] .getSize (); 파일 f = 새 파일 (로컬); 긴 현지 크기 = F.length (); if (remotesize == localalsize) {return uploadstatus.file_exits; } else if (remotesize> localsize) {return uploadstatus.remote_bigger_local; } // 파일의 포인터를 이동하여 중단 점 INPUTSTREAM의 중단이 = 새로운 FileInputStream (f); if (is.skip (remotesize) == remotesize) {ftpclient.setRestArtOffset (remotesize); if (ftpclient.storefile (remote, is)) {return uploadstatus.upload_from_break_success; }} // 브레이크 포인트의 인터럽트가 성공하지 못하면 서버에서 파일을 삭제하고 (! ftpclient.deletefile (remoteFilename)) {return uploadstatus.delete_remote_faild; } is = new FileInputStream (f); if (ftpclient.storefile (remote, is)) {result = uploadstatus.upload_new_file_success; } else {result = uploadstatus.upload_new_file_failed; } is.close (); } else {inputStream은 = new FileInputStream (local); if (ftpclient.storefile (remoteFilename, is)) {result = uploadstatus.upload_new_file_success; } else {result = uploadstatus.upload_new_file_failed; } is.close (); } 반환 결과; } / ** * * 원격 서버에서 분리 * * @Throws ioException * / public void Disternect ()는 ioexception {if (ftpclient.isconnected ()) {ftpclient.disconnect (); }} public static void main (string [] args) {weantftp myftp = new windingftp (); try {myftp.connect ( "192.168.1.200", 21, "Duser", "htpduserxp32"); system.out.println (myftp.upload ( "c : //users//administrator//desktop//swing.drawer.jar", "/jars/swing.drawer.jar")); myftp.disconnect (); } catch (ioException e) {System.out.println ( "ftp에 연결하는 오류 :" + e.getMessage ()); }}} 위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.