FTP는 파일 전송 프로토콜 (파일 전송 프로토콜)의 영어 약어이며 중국어 약어를 "서면 전송 프로토콜"이라고합니다. 인터넷에서 제어 파일의 양방향 전송에 사용됩니다. 동시에, 그것은 또한 응용 프로그램이기도합니다. 다른 운영 체제를 기반으로 다른 FTP 응용 프로그램이 있으며, 이러한 모든 응용 프로그램은 파일을 전송하기 위해 동일한 프로토콜을 준수합니다. FTP를 사용하면 사용자는 종종 "다운로드"와 "업로드"라는 두 가지 개념에 직면합니다. "다운로드"파일은 원격 호스트에서 자신의 컴퓨터로 파일을 복사하는 것을 의미합니다. "업로드"파일은 자신의 컴퓨터에서 원격 호스트로 파일을 복사하는 것을 의미합니다. 인터넷 언어에서 사용자는 클라이언트 프로그램을 통해 원격 호스트에 파일을 업로드 (다운로드) 할 수 있습니다.
먼저, Serv-U는 컴퓨터를 FTP 파일 서버로 설정하여 쉽게 작동 할 수 있도록 다운로드되었습니다. 다음 코드는 FTP 서버에서 사용되며 FTP 연결의 관련 데이터는 코드에 작성되어이를 완료해야합니다.
1. FTP 파일의 업로드 및 다운로드 (개별 파일의 업로드 및 다운로드입니다)
import java.io.file; import java.io.fileinputStream; import java.io.filenotfoundException; import java.io.fileoutputStream; import java.io.ioexception; import java.io.inputStream; import java.io.outputStream; import org.apache.commons.net.ft.ftp; org.apache.commons.net.ftp.ftpclient; import org.apache.commons.net.ftp.ftpfile; import org.apache.commons.net.ftp.ftpreply;/*** 구현 ftp 파일 업로드 및 파일 다운로드*/public class ftpapche {private static ftpclient ftpclient = 새로운 ftpclient (); 개인 정적 문자열 인코딩 = System.GetProperty ( "file.encoding"); /** * 설명 : ftp 서버 * @version1.0 * @param url * ftp server hostname * @param port * ftp server port * @param username * ftp login 계정 * @param password * ftp login password * @param path * ftp 서버 저장 디렉토리 인 경우, @param potleam * 파일 " ftp server * @param input * 로컬 파일 입력 스트림 * @return true가 성공적으로 반환합니다. 그렇지 않으면 false */ public static boolean uploadfile (문자열 URL, int 포트, 문자열 사용자 이름, 문자열 경로, 문자열 파일 이름, 입력 스트림 입력) {boolean result = false; {int reply; // 기본 포트를 사용하는 경우 FTP 서버 ftpclient.connect (url)에 직접 연결할 수 있습니다. // ftp.connect (url, port); // ftp server를 연결 // 로그인하면 ftpclient.login (username, password); ftpclient.setcontrolencoding (인코딩); // 연결이 성공적인지 확인 = ftpclient.getReplyCode (); if (! ftpReply.ispositiveCompletion (reply)) {System.out.println ( "연결 실패"); ftpclient.disconnect (); 반환 결과; } // 지정된 디렉토리로 작업 디렉토리를 전송 부울 변경 = ftpclient.changeworkingDirectory (PATH); ftpclient.setfiletype (ftp.binary_file_type); if (change) {result = ftpclient.storefile (new String (filename.getBytes (인코딩), "ISO-8859-1"), 입력); if (result) {system.out.println ( "성공적으로 업로드!"); }} input.close (); ftpclient.logout (); } catch (ioexception e) {e.printstacktrace (); } 마지막으로 {if (ftpclient.isconnected ()) {try {ftpclient.disconnect (); } catch (ioexception ioe) {}}} return result; }/*** FTP 서버에 로컬 파일을 업로드*/public void testuploadfromdisk () {try {fileInputStream in = new FileInputStream ( "d : /test02/list.txt"); 부울 플래그 = uploadfile ( "10.0.0.102", 21, "admin", "123456", "/", "lis.txt", in); System.out.println (플래그); } catch (filenotfoundException e) {e.printstacktrace (); }} /** * 설명 : ftp 서버에서 파일을 다운로드 * @version1.0 * @param url * ftp server hostname * @param port * ftp server port * @param username * ftp 로그인 계정 * @param password * ftp login * @param Remotepath * @param server * @param store * @param name * @param local path * @param remotepath * 다운로드 후 * @return */ public static boolean downfile (문자열 URL, int port, 문자열 사용자 이름, 문자열 암호, 문자열 remotepath, 문자열 파일 이름, 문자열 로컬 경로) {boolean result = false; {int reply; ftpclient.setcontrolencoding (인코딩); / * * 중국어 파일을 업로드하고 다운로드하려면 일부 장소에서는 * 새 문자열 대신 다음 두 문장을 사용하는 것이 좋습니다 (remotepath.getBytes (인코딩), "ISO-8859-1") 트랜스 코딩. * 테스트 후 통과 할 수 없습니다. */// ftpclientConfig conf = new ftpclientConfig (ftpclientConfig.syst_nt); // conf.SetServerLanguageCode ( "ZH"); ftpclient.connect (URL, 포트); // 기본 포트가 사용되면 ftpclient.login (사용자 이름, 암호); // login // 파일 전송 유형을 Binary ftpclient.setFileType (ftpclient.binary_file_type)로 설정하여 ftpclient.login (username, password); // ftp 서버에 직접 연결할 수 있습니다. // ftp 로그인 응답 코드를 가져옵니다. 답장 = ftpclient.getReplyCode (); // 로그인이 성공했는지 확인하십시오 (! ftpReply.ispositiveCempletion (reply)) {ftpclient.disconnect (); System.err.println ( "FTP 서버가 연결을 거부했습니다."); 반환 결과; } // 지정된 디렉토리 ftpclient.changeworkingDirectory로 FTP 서버 디렉토리로 전송합니다 (새 String (remotepath.getBytes (인코딩), "ISO-8859-1"); // 파일 목록 가져 오기 ftpfile [] fs = ftpclient.listfiles (); for (ftpfile ff : fs) {if (ff.getname (). equals (filename)) {file localfile = 새 파일 (localPath + "/" + ff.getName ()); outputStream은 = 새 파일 아웃 putStream (localfile); ftpclient.retrivefile (ff.getName (), is); is.close (); }} ftpclient.logout (); 결과 = true; } catch (ioexception e) {e.printstacktrace (); } 마지막으로 {if (ftpclient.isconnected ()) {try {ftpclient.disconnect (); } catch (ioexception ioe) {}}} return result; }/** * ftp 서버의 파일을 로컬 */public void testdownfile () {try {boolean flag = downfile ( "10.0.0.102", "admin", "123456", "/", "ip.txt", "e :/"); System.out.println (플래그); } catch (예외 e) {e.printstacktrace (); }} public static void main (String [] args) {ftpapche fa = new ftpapche (); fa.testdownfile (); fa.testuploadfromdisk (); }}2. FTP 폴더의 업로드 및 다운로드 (전체 폴더가 전체 폴더임을 참고하십시오)
패키지 ftp; import java.io.bufferedInputStream; import java.io.bufferedoutputStream; import java.io.file; import java.io.fileInputStream; import java.io.filenotfoundException; import java.io.fileoutputstream; import java.io.ioexcemplement; org.apache.commons.net.ftp.ftpclient; import org.apache.commons.net.ftp.ftpclientconfig; import org.apache.commons.net.ftp.ftpfile; import org.apache.commons.net.tf.ftpreply; import org.apache.log4j.logger; ftpclient ftpclient; 개인 문자열 스트립; 개인 intport; 개인 문자열 사용자; 개인 문자열 비밀번호; 개인 정적 로거 로거 = logger.getLogger (ftptest_04.class.getName ()); / * * * ftp 생성자 */ public ftptest_04 (문자열 스트립, intpport, 문자열 사용자, 문자열 암호) {this.strip = strip; this.intport = intport; this.user = 사용자; this.password = 비밀번호; this.ftpclient = new ftpclient (); } / *** @return 로그인이 성공했는지 여부** / public boolean ftplogin () {boolean islogin = false; ftpclientConfig ftpclientConfig = 새로운 ftpclientConfig (); ftpclientconfig.setservertimezoneid (timezone.getDefault (). getId ()); this.ftpclient.setcontrolencoding ( "gbk"); this.ftpclient.configure (ftpclientConfig); try {if (this.intport> 0) {this.ftpclient.connect (this.strip, this.intport); } else {this.ftpclient.connect (this.strip); } // ftp 서버 연결 답변 int reply = this.ftpclient.getReplyCode (); if (! ftpReply.ispositiveCompletion (답장)) {this.ftpclient.disconnect (); logger.error ( "FTP 서비스에 로그인이 실패했습니다!"); 반환 이슬 로그; } this.ftpclient.login (this.user, this.password); // 전송 프로토콜을 설정 this.ftpclient.enterlocalPassiveMode (); this.ftpclient.setFileType (ftpclient.binary_file_type); logger.info ( "축하" + this.user + "FTP 서버에 성공적으로 로그인 됨"); Islogin = true; } catch (예외 e) {e.printstacktrace (); logger.error (this.user + "FTP 서비스에 로그인 실패!" + e.getMessage ()); } this.ftpclient.setbuffersize (1024 * 2); this.ftpclient.setDatatimeout (30 * 1000); 반환 이슬 로그; }/ *** @exit Close 서버 링크**/ public void ftplogout () {if (null! = this.ftpclient && this.ftpclient.isconnected ()) {try {boolean reuslt = this.ftpclient.logout (); // exit ftp server if (reuslt) { "); }} catch (ioexception e) {e.printstacktrace (); logger.warn ( "FTP 서버 종료 예외!" + e.getMessage ()); } 마지막으로 {try {this.ftpclient.disconnect (); // ftp 서버에 연결을 닫습니다} catch (ioException e) {e.printstackTrace (); logger.warn ( "FTP 서버의 연결을 닫는 예외!"); }}}}}}/**** ftp 파일을 업로드* @param localfile local file* @param romotuploadepath 서버 경로 업로드-/**/public boolean uploadfile (파일 로컬 파일, String RomotuploadePath) {bufferedInputStream = null; 부울 성공 = 거짓; try {this.ftpclient.changeworkingdirectory (romotuploadepath); // 작동 경로 변경 instream = new bufferedInputStream (new FileInputStream (localFile)); logger.info (localfile.getName () + "시작 업로드 ..."); success = this.ftpclient.storefile (localfile.getName (), instream); if (success == true) {logger.info (localfile.getName () + "성공적으로 업로드 됨"); 반환 성공; }} catch (filenotfoundException e) {e.printstacktrace (); logger.error (localfile + "찾기 없음"); } catch (ioexception e) {e.printstacktrace (); } 마침내 {if (instream! = null) {try {instream.close (); } catch (ioexception e) {e.printstacktrace (); }}} 반환 성공; } / **** 다운로드 파일* @param remoteFilename 파일 이름을 다운로드 할* @param localDires 로컬 경로에 다운로드* @param remotedownloadpath remoteFilename이 위치한 경로** / public boolean downloadfile (String RemoteFilename, String LocalDires, String RemotedownloadPath) {String strfileth = localDires + OrmoteFilename; BufferedOutputStream Outstream = null; 부울 성공 = 거짓; try {this.ftpclient.changeworkingDirectory (RemotedOwnLoadPath); OutStream = 새로운 BufferedOutputStream (new FileOutputStream (strfilepath)); logger.info (remoteFilename + "시작 다운로드 ..."); success = this.ftpclient.retrivefile (remotefilename, etstream); if (success == true) {logger.info (remotefilename + "성공적으로" + strfilepath에 다운로드); 반환 성공; }} catch (예외 e) {e.printstacktrace (); logger.error (RemoteFilename + "다운로드 실패"); } 마침내 {if (null! = etstream) {try {outstream.flush (); Outstream.close (); } catch (ioexception e) {e.printstacktrace (); }}} if (success == false) {logger.error (remoteFilename + "다운로드 실패 !!!"); } 반환 성공; }/**** @upload 폴더* @param localDirectory* 로컬 폴더* @param RemotedirectoryPath* ftp 서버 경로는 디렉토리로 끝납니다. {RemotedirectoryPath = RemotedirectoryPath + src.getName () + "/"; 부울 makedirflag = this.ftpclient.makedirectory (remotedirectorypath); System.out.println ( "LocalDirectory :" + localDirectory); System.out.println ( "RemotedirectoryPath :" + RemotedirectoryPath); System.out.println ( "src.getName () :" + src.getName ()); System.out.println ( "RemotedirectoryPath :" + RemotedirectoryPath); System.out.println ( "Makedirflag :" + Makedirflag); // ftpclient.listDirectories (); } catch (ioexception e) {e.printstacktrace (); logger.info (RemotedirectoryPath + "디렉토리 생성 실패"); } file [] allfile = src.listfiles (); for (int currentFile = 0; currentFile <allFile.Length; currentFile ++) {if (! allFile [currentFile] .isdirectory ()) {String srcName = allFile [currentFile] .getPath (). toString (); uploadfile (새 파일 (srcname), remotedirectoryPath); }} for (int currentFile = 0; currentFile.length; currentFile ++) {if (allFile [currentFile] .isdirectory ()) {// recursive uploadDirectory (allFile [currentFile] .getPath (). toString (), RemotedIrectoryPath); }} true를 반환합니다. } / **** @download 폴더* @param localDirectoryPath 로컬 주소* @param remotedirectory 원격 폴더* / public boolean downloadDirectory (String localDirectoryPath, String Remotedirectory) {try {string {string filename = 새 파일 (remotedirectory) .getName (); LocalDirectoryPath = LocalDirectoryPath + filename + "//"; 새 파일 (localDirectoryPath) .mkdirs (); ftpfile [] allfile = this.ftpclient.listfiles (remotedirectory); for (int currentFile = 0; currentFile <allFile.length; currentFile ++) {if (! allfile [currentFile] .isdirectory ()) {downloadFile (allfile [currentFile] .getName (), localDirectoryPath, RemoteDerectory); }} for (int currentFile = 0; currentFile.Length; currentFile ++) {if (allFile [currentFile] .isdirectory ()) {String strremotedirectoryPath = Remotedirectory+ "/"+ allfile [currentFile] .getName (); DownloadDirectory (LocalDirectoryPath, StrremotedirectoryPath); }}} catch (ioexception e) {e.printstacktrace (); logger.info ( "다운로드 폴더 실패"); 거짓을 반환합니다. } true를 반환합니다. } // ftpclient set and get functions public ftpclient getftpclient () {return ftpclient; } public void setftpclient (ftpclient ftpclient) {this.ftpclient = ftpclient; } public static void main (String [] args)은 ioexception {ftptest_04 ftp = new ftptest_04 ( "10.0.0.102", 21, "admin", "123456"); ftp.ftplogin (); System.out.println ( "1"); // 폴더 업로드 boolean uploadflag = ftp.uploaddirectory ( "d : // test02", "/"); // admin/인 경우 모든 파일이 전달됩니다. 단지/인 경우 폴더 System.out.println ( "uploadflag :" + uploadflag)에 전달됩니다. // 폴더 다운로드 ftp.downloadDirectory ( "d : // tm", "/"); ftp.ftplogout (); }}위는이 기사의 모든 내용입니다. 이 기사의 내용이 모든 사람의 연구 나 업무에 도움이되기를 바랍니다. 또한 wulin.com을 더 지원하기를 바랍니다!