この記事では、主にApache Toolset Commons-Netが提供するFTPツールを使用してFTPサーバーにファイルをアップロードおよびダウンロードする方法を紹介します。
1。準備
commons-net-3.5.jarパッケージを参照する必要があります。
Mavenを使用してインポート:
<Dependency> GroupId> commons-net </groupid> <artifactid> commons-net </artifactid> <version> 3.5 </version> </dependency>
マニュアルダウンロード:
//www.vevb.com/softs/550085.html
2。FTPサーバーに接続します
/** * ftp serverに接続 * @throws ioexception */public static final string anonymous_user = "anonymous"; private ftpclient connect(){ftpclient client = new ftpclient(); try {// connect ftp serverclient.connect(this.host、this.port); if(this.user == null || ""。equals(this.user)){// client.login(anonymous_user、anonymous_user);} els {client.login(this.user、this.password);} //ファイルのファイル形式の設定クライアント。返信int Reply = client.getReplyCode(); if(!ftpreply.ispositiveCompletion(Reply)){client.disconnect(); return null;} //ワーキングディレクトリChangeWorkingDirectory(client); system.out.println( "==="+host+" null;} return client;}/***作業ディレクトリを切り替えます。リモートディレクトリが存在しない場合は、ディレクトリ * @paramクライアント * @throws ioexception */private void changeworkingdirectory(ftpclient client)を作成します{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);}}}}/** * @param ftpclient * @throws ioexception */public void close(ftpclient ftpclient)shrows ioexception! ftpclient.isconnected()){ftpclient.logout(); ftpclient.disconnect();} system.out.println( "!!! disconnectftp connection:"+host+":"+port);}ホスト:FTPサーバーIPアドレス
ポート:FTPサーバーポート
ユーザー:ログインユーザー
パスワード:ログインパスワードが空の場合は、匿名のユーザーを使用してログインします。
FTPPATH:FTPパスが存在しないときに自動的に作成されたFTPパス。多層ディレクトリ構造の場合、ディレクトリを繰り返し作成する必要があります。
3。ファイルをアップロードします
/**アップロードファイル* @Param TargetName FTPファイル名にアップロード* @param localFileローカルファイルパス*/public boolean upload(string targetname、string localfile){// connect ftp serverftpclient ftpClient = connect(); server ["+host+": "+port+"] failed! "); return false;} file file = new file(localfile); //アップロード後にファイル名を設定します(ターゲットネーム== null ||" "。 new FileInputStream(file); system.out.println( ">>> file:+file.getName()); boolean ok = ftpclient.storefile.storefile(fis、fis); if(ok); if(ok);サイズ:%s、アップロード時間:%d秒 "、Formatize(file.length())、times/1000)失敗:size:%s "、formatsize(file.length())); e.printstacktrace(); return false;}最後に{if(fis!= null)fis.close(); close(ftpclient);} catch(exception e){}} return true;}4.ファイルをダウンロードします
/*** @param localpathローカルストレージパス* @return*/public int download(string localpath){// ftp serverftpclient ftpclient = connect(); if(ftpclient == null){system.out.println( "connect ftp server ["+host+":"+port+";"+port+";") file(localpath); if(!dir.exists())dir.mkdirs(); ftpfile [] ftpfiles = null; try {ftpclient.listfiles(); if(ftpfiles == null || ftpfiles.length == initexception 0;} catch(IoException e) i = 0; i <ftpfiles.length; i ++){fileoutputstream fos = null; try {string name = ftpfiles [i] .getName(); fos = new fileoutputStream(new file(dir.getabsolutepath()+file.separator+name)) long now = system.currenttimemillis(); boolean ok = ftpclient.retrieveFile(new String(name.getBytes( "utf-8")、 "ISO-8859-1")、fos);サイズ:%s、アップロード時間:%d秒 "、フォーマット化(ftpfiles [i] .getSize())、times/1000); c ++;}最後に{try {if(fos!= null)fos.close(); close(ftpclient);} catch(exception e){}}} return c;}ファイルサイズのフォーマット
private static final decimalformat df = new decimalformat( "#。##"); / ** *フォーマットファイルサイズ(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、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>>>> ASTARTアップロードファイル:TeamViewerPortable.RAR >>>アップロードされました:サイズ:5 MB、アップロード時間:3秒!!! newfile.rar <<< sucessに発見:サイズ:5 MB、アップロード時間:4秒!!! FTP接続を切断:192.168.1.10:21
要約します
上記は、FTPファイル転送コードを実装するためのJavaのApacheツールセットの使用に関する詳細な説明です。すべての人に役立つことを願っています。興味のある友人は、このサイトの他の関連トピックを引き続き参照できます。欠点がある場合は、それを指摘するためにメッセージを残してください。このサイトへのご支援をありがとうございました!