이 기사는 주로 Apache Toolset Commons-Net에서 제공하는 FTP 도구를 사용하여 파일을 FTP 서버에 업로드하고 다운로드하는 방법을 소개합니다.
1. 준비
Commons-Net-3.5.jar 패키지를 참조해야합니다.
Maven을 사용하여 가져 오기 :
<pectionency> <groupId> Commons-Net </groupid> <artifactid> Commons-Net </artifactid> <bersion> 3.5 </version> </fectionency>
수동 다운로드 :
//www.vevb.com/softs/550085.html
2. FTP 서버에 연결하십시오
/** * ftp 서버에 연결 * @throws ioexception */public static final string anonymous_user = "익명"; private ftpclient connect () {ftpclient client = new ftpclient (); // ftp serverclient.connect (this.host, this.port); // login을 연결하십시오. if (this.user == null || "". equals (this.user))) {// client.login (anyfilous_user, anonymous_user);} else {client.login (this.user, this.password);} // set format.setfiletp get ft the ft the ft the ft the ft the ft the ft the ft the ft the ft the ft the ft the ft the ft the get the ft the ft the get the ft the for reply = client.getReplyCode (); if (! ftpReply.ispositiveCompletion (reply)) {client.disconnect (); return null;} // 작업 디렉토리 change changeworkingDirectory (client); system.out.println ( "=== Connect :"+host+"; 클라이언트;}/*** 작업 디렉토리를 전환합니다. 원격 디렉토리가 존재하지 않으면 디렉토리 * @param client * @throws ioexception */private void changeworkingdirectory (ftpclient client)가 ioexception {if (this.ftppath! = null &&! "". client.changeworkingdirectory (this.ftppath); if (! ok) {// ftppath가 존재하지 않는다. 디렉토리를 수동으로 stringtokenizer token = new StringTokenizer (this.ftppath, "///"); token.nextToken (); client.makedirectory (path); client.ChangeWorkingDirectory (Path);}}}/** * ** * FTP 연결을 연결 해제 * @param ftpclient * @throws ioexception */public void close (ftpclient ftpclient) ioexction ioexception (ftpclient! if). ftpclient.isconnected ()) {ftpclient.logout (); ftpclient.disconnect ();} system.out.println ( "!!! Disponnectftp 연결 :"+host+":"+port);} 호스트 : FTP 서버 IP 주소
포트 : FTP 서버 포트
사용자 : 로그인 사용자
비밀번호 : 로그인 비밀번호가 비어 있으면 익명 사용자를 사용하여 로그인하십시오.
ftppath : FTP 경로가 존재하지 않을 때 자동으로 생성 된 FTP 경로. 다층 디렉토리 구조 인 경우 디렉토리를 반복적으로 만들어야합니다.
3. 파일 업로드
/*** 파일 업로드* @Param TargetName FTP 파일 이름에 업로드* @param localfile local file path* @return*/public boolean upload (string targetName, String LocalFile) {// connect ftp serverftpclient ftpclient = connect (); if (ftpclient == null) {system.out.out.ptprintln ( "connect to ftprintln 서버 [ "+host+": "+port+"] 실패! "); return; return;} 파일 파일 = 새 파일 (localFile); // 업로드 후 파일 이름을 설정합니다 (targetName == null ||" ". FileInputStream (file); system.out.println ( ">>> 파일 업로드 시작 :"+file.getName ()); boolean ok = ftpclient.storefile (targetName, fis); if (OK) {// Uploy Times = System.currentTimeMillis () - 이제 string.format (syning.format ( "). %s, 업로드 시간 : %d seconds ", formatsize (file.length ()), times/1000));} else // Upload 실패 System.out.out.println (String.format (">>> 업로드 실패 : size : %s ");} catch (io -exception e) {system.err.err.println (strintln). %s ", formatsize (file.length ())); e.printstacktrace (); return false;} 마지막으로 {try {if (fis! = null) fis.close (); Close (ftpclient);} catch (예외 e)} retry true;}.4. 파일을 다운로드하십시오
/*** 파일 다운로드* @param localpath 로컬 스토리지 경로* @return*/public int download (string localpath) {// ftp serverftpclient에 연결 ftpclient = connect (); if (ftpclient == null) {system.out.println ( "+host+": "+port+"]; return 0; file (localPath); if (! dir.exists ()) dir.mkdirs (); ftpfile [] ftpfiles = null; try {ftpfiles = ftpclient.listfiles (); if (ftpfiles == null || ftpfiles.length == 0;} return 0;} 0; i = 0; i <ftpfiles.length; i ++) {fileoutputstream fos = null; try {string name = ftpfiles [i] .getname (); fos = new FileOutputStream (새 파일 (dir.getAbsolutePath ()+file.separator+name); system.out.println ( "<<+파일); long now = system.currenttimeMillis (); boolean ok = ftpclient.retrieveFile (new String ( "utf-8"), "iso-8859-1"), fos); if (ok) {// system.crintln (strint.println : : "<< << << <size.println. %s, 업로드 시간 : %d seconds ", 형식 (ftpfiles [i] .getsize ()), times/1000)); c ++;} else {system.out.println ("<<< 다운로드 실패 ");}} catch (ioexception e) {system.err.println ("<<<}; 마지막으로 {try {if (fos! = null) fos.close (); close (ftpclient);} catch (예외 e) {}}} return c;}형식 파일 크기
Private STATIC Final DecimalFormat DF = 새로운 소수성 ( "#. ##"); / ** * 형식 파일 크기 (b, kb, mb, gb) * @param size * @return */ private string formatsize (long size) {if (size <1024) {return size + "b"; } else if (size <1024*1024) {return size/1024 + "kb"; } else if (size <1024*1024*1024) {return (size/(1024*1024)) + "mb"; } else {double gb = size/(1024*1024*1024); df.format (GB)+"GB"를 반환합니다. }}V. 테스트
public static void main (String args []) {ftptest ftp = new ftptest ( "192.168.1.10", 21, null, "/temp/2016/12"); ftp.upload ( "newfile.rar", "d : /ftp/teamviewerportable.rar"); System.out.println ( ""); ftp.download ( "d :/ftp/"); }결과
=== FTP에 연결 : 192.168.1.10:21>>>>>> >>> ipload 파일 : teamViewErportable.rar >>> 성공적으로 업로드 : 크기 : 5MB, 업로드 시간 : 3 초 !!! 연결이 끊어진 FTP 연결 : 192.168.1.10:21== Connect to FTP : 192.168.1.11.21<< 21:21< 2168. NewFile.rar <<< 성공적으로 발견 : 크기 : 5MB, 업로드 시간 : 4 초 !!! 연결이 끊어진 FTP 연결 : 192.168.1.10:21
요약
위의 내용은 Java가 FTP 파일 전송 코드를 구현하기 위해 Apache Toolset 사용에 대한 자세한 설명입니다. 모든 사람에게 도움이되기를 바랍니다. 관심있는 친구는이 사이트의 다른 관련 주제를 계속 참조 할 수 있습니다. 단점이 있으면 메시지를 남겨 두십시오. 이 사이트를 지원해 주신 친구들에게 감사드립니다!