FTPClient(Kotlin)
- 2020.03.29
- Android

以下を参考にFTP通信でファイルのアップロードを行うアプリを作っていたものの、KotlinにFTPClientクラスがなかった。
参考:AndroidでAsyncTaskを使いFTP送信をする 非同期処理でのFTPクライアントの実装
変わりになりそうなライブラリーをstackoverflowで発見
参考:How to use the FTP to upload a small file or an image in android studio using Kotlin
ftp4jのダウンロード
ダウンロード:http://www.sauronsoftware.it/projects/ftp4j/index.php
ダウンロードしたら展開、中にあるftp4j-1.7.2.jarファイルをプロジェクト内のapp/libsに入れる。
ftp4j実装
以下のように使う。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
// FTPクライアント private inner class FTP(base: Context?) : ContextWrapper(base) { fun putData( remoteserver: String, //FTPサーバーアドレス remoteport: Int, //FTPサーバーポート userid: String, //サーバーフォルダ passwd: String, //ログインユーザID passive: Boolean, //ログインパスワード remotefile: String, //パッシブモード使用 data:String //送信データ ): String? { myFTPClient = FTPClient() try { //接続 myFTPClient!!.connect(remoteserver, remoteport) myFTPClient!!.login(userid, passwd) //転送モード(パッシブ) myFTPClient!!.isPassive = passive myFTPClient!!.changeDirectory(remotefile) //ファイルアップロード val file = File(data) myFTPClient!!.upload(file) //ログアウト myFTPClient!!.logout() //切断 myFTPClient!!.disconnect(true) } catch (e: Exception) { return e.message } catch (e: FTPException) { return e.message }finally { if (myFTPClient!!.isConnected()) { try { myFTPClient!!.disconnect(true) } catch (e: IOException) { } } myFTPClient = null } return null } } |
各手順で例外が発生した場合、FTPExceptionを受け取る。
また、ログイン、ファイルアップロードが終わり次第disconnect(true)で閉じる。
ちなみにtrueにすることでFTP QUITコマンドによる切断要求を送信できる。
単に切断するだけであればfalseで良い。
FTPS / FTPES両方をサポートしているため出来次第また更新する予定。
-
前の記事
ギャラリーから画像/動画を取得する 2020.03.24
-
次の記事
DiscordでBotを作成する(導入編) 2020.04.26