android ftp用戶端開發

來源:互聯網
上載者:User

    FTP用戶端實則是相對於遠程檔案的一個檔案管理工具,主要的功能有登入,下載,上傳,剪下,粘貼,建立檔案夾,重新命名,刪除檔案,查看檔案屬性,同步等等。其實同步也就是上傳,只是把上傳功能修飾了一下罷了,應用需要引入一個ftp4j.jar的庫。那就先說說整個用戶端的代碼邏輯吧。

使用者進入應用後首先進入的是登入串連伺服器,擷取一個ftpclient引用,有了它你就能為所欲為了,呵。擷取ftpClient之後我們就可以進行檔案瀏覽和操作了,檔案操作大都比較簡單,就挑幾個重點的吧。一個是剪下,剪下的時候只需要將選擇的檔案的絕對路徑儲存到SharedPreferences,等到調用粘貼的時候再調用剪下ftpClient.reName(oldName,newName)方法便可實現剪下功能。另一個就是同步,同步功能是將從服務端下載過而在本地又修改過的資源進行上傳進而覆蓋掉服務端的資源,達到更新的目的。筆者實現同步功能的做法是首先在下載的時候將下載的檔案對應於服務端的絕對路徑、下載時間、下載到本地的路徑儲存於資料庫,每次使用者進入應用的時候對資料庫進行更新,將存在有記錄而沒有對應檔案的記錄刪除。然後當使用者點擊同步的時候就逐一進行最後修改時間對比,找到有修改過的檔案便對其進行上傳到ftp的相應目錄進行覆蓋,再對資料庫進行更新。

ftp基本作業碼

/** * 刪除伺服器上指定檔案 *  * @throws FTPException * @throws FTPIllegalReplyException * @throws IOException * @throws IllegalStateException * */public static void removeFTPFile(FTPClient ftpClient,String removeFilePath, boolean isDirectory)throws IllegalStateException, IOException,FTPIllegalReplyException, FTPException {if (isDirectory) {ftpClient.deleteDirectory(removeFilePath);return;}ftpClient.deleteFile(removeFilePath);}/** * 給伺服器上的檔案進行重新命名 * */public static void renameFTPFile(Context context,final FTPClient ftpClient, final FTPFile file) {Builder builder = new AlertDialog.Builder(context);// 設定對話方塊的標題builder.setTitle("重新命名");final EditText edit = new EditText(context);edit.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));edit.setHint(file.getName());builder.setView(edit);builder.setPositiveButton("確定", new OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {if (edit.getText() != null && !"".equals(edit.getText())) {try {ftpClient.rename(file.getName(), edit.getText().toString());} catch (Exception e) {e.printStackTrace();}}}});builder.setNegativeButton("取消", new OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.dismiss();}});builder.create().show();}/** * 剪下 * */public static void cutFTPFile(SavePreferencesData savePreData,String cutFTPFileAbsolutePath) {savePreData.putStringData("cut", cutFTPFileAbsolutePath);}/** * 粘貼 *  * @throws FTPException * @throws FTPIllegalReplyException * @throws IOException * @throws IllegalStateException * */public static void pasteFTPFile(SavePreferencesData savePreData,FTPClient ftpClient, String newPath) throws IllegalStateException,IOException, FTPIllegalReplyException, FTPException {String cutPath = savePreData.getStringData("cut");if (!"".equals(cutPath)) {ftpClient.rename(cutPath,newPath+ "/"+ cutPath.substring(cutPath.lastIndexOf("/") + 1,cutPath.length()));savePreData.clear();}}/** * 顯示檔案屬性 * */public static void showFTPFileProperty(Context context, FTPFile file) {Builder builder = new AlertDialog.Builder(context);// 設定對話方塊的標題builder.setTitle("屬性");String type = file.getType() == FTPFile.TYPE_DIRECTORY ? "檔案夾" : "檔案";builder.setMessage("檔案名稱: " + file.getName() + " \n 檔案類型: " + type+ "\n 檔案大小: " + file.getSize() + " 位元組 \n 上次修改時間: "+ file.getModifiedDate());builder.create().show();}/** * 下載指定檔案 * */public static void downloadFTPFile(FTPUtil util, Map<String, String> item) {util.setFile(item);util.preTransFile();}/** * 建立檔案夾 * */public static void newFTPFileDirectory(Context context,final FTPClient ftpClient) throws IllegalStateException,IOException, FTPIllegalReplyException, FTPException {Builder builder = new AlertDialog.Builder(context);// 設定對話方塊的標題builder.setTitle("建立檔案夾");final EditText edit = new EditText(context);edit.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));builder.setView(edit);builder.setPositiveButton("確定", new OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {if (edit.getText() != null && !"".equals(edit.getText())) {try {ftpClient.createDirectory(edit.getText().toString());} catch (Exception e) {e.printStackTrace();}}}});builder.setNegativeButton("取消", new OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.dismiss();}});builder.create().show();}

ftp上傳下載功能實現

/** * 傳輸檔案 *  * @throws FTPAbortedException * @throws FTPDataTransferException * @throws FTPException * @throws FTPIllegalReplyException * @throws IOException * @throws FileNotFoundException * @throws IllegalStateException */private void transFile() throws IllegalStateException,FileNotFoundException, IOException, FTPIllegalReplyException,FTPException, FTPDataTransferException, FTPAbortedException {operateType = (String) mQueue.get(0).keySet().toArray()[0];filePath = mQueue.get(0).get(operateType);if (operateType.equals(Constants.TYPE_DOWNLOAD)) {File file = new File(Constants.workSpace+ filePath.substring(filePath.lastIndexOf("/") + 1,filePath.length()));mFtpClient.download(filePath, file, new MyFTPDataTransferListener());} else if (operateType.equals(Constants.TYPE_UPLOAD)) {File file = new File(filePath);if (file.exists()) {System.out.println("upload path ----> " + uploadPathQueue.get(0));mFtpClient.changeDirectory(uploadPathQueue.get(0));mFtpClient.upload(file, new MyFTPDataTransferListener());}}}

ftp登入和登出功能

/** * 這裡在外面有非ui線程來處理 *  * @param host *            ftp主機 * @param port *            連接埠 * @param username *            使用者名稱 * @param password *            密碼 */public FTPClient login(String host, int port, String username,String password) {if (null != mFtpClient)return mFtpClient;try {mFtpClient = new FTPClient();mFtpClient.connect(host, port);mFtpClient.login(username, password, null);return mFtpClient;} catch (Exception e) {e.printStackTrace();Toast.makeText(context, "串連伺服器失敗", Toast.LENGTH_LONG).show();}return null;}/** * 登出 */public void logout() {if (null != mFtpClient) {try {mFtpClient.logout();mFtpClient.disconnect(true);} catch (IOException e) {e.printStackTrace();} catch (FTPIllegalReplyException e) {e.printStackTrace();} catch (FTPException e) {e.printStackTrace();}}}

最後提供一下源碼下載吧;點擊開啟連結

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.