獲取Android文件信息

2018-08-02 17:30 更新

編寫(xiě):jdneo - 原文:http://developer.android.com/training/secure-file-sharing/retrieve-info.html

當(dāng)一個(gè)客戶端應(yīng)用程序擁有了文件的Content URI之后,它就可以獲取該文件并進(jìn)行下一步的工作了,但在此之前,客戶端應(yīng)用程序還可以向服務(wù)端應(yīng)用程序獲取關(guān)于文件的信息,包括文件的數(shù)據(jù)類型和文件大小等等。數(shù)據(jù)類型可以幫助客戶端應(yīng)用程序確定自己能否處理該文件,文件大小能幫助客戶端應(yīng)用程序?yàn)槲募O(shè)置合理的緩沖區(qū)。

本課將展示如何通過(guò)查詢服務(wù)端應(yīng)用程序的FileProvider來(lái)獲取文件的MIME類型和文件大小。

獲取文件的MIME類型

客戶端應(yīng)用程序可以通過(guò)文件的數(shù)據(jù)類型判斷自己應(yīng)該如何處理這個(gè)文件的內(nèi)容??蛻舳藨?yīng)用程序可以通過(guò)調(diào)用ContentResolver.getType()方法獲得Content URI所對(duì)應(yīng)的文件數(shù)據(jù)類型。該方法返回文件的MIME類型。默認(rèn)情況下,一個(gè)FileProvider通過(guò)文件的后綴名來(lái)確定其MIME類型。

下例展示了當(dāng)服務(wù)端應(yīng)用程序?qū)ontent URI返回給客戶端應(yīng)用程序后,客戶端應(yīng)用程序應(yīng)該如何獲取文件的MIMIE類型:

    ...
    /*
     * Get the file's content URI from the incoming Intent, then
     * get the file's MIME type
     */
    Uri returnUri = returnIntent.getData();
    String mimeType = getContentResolver().getType(returnUri);
    ...

獲取文件名及文件大小

FileProvider類有一個(gè)query()方法的默認(rèn)實(shí)現(xiàn),它返回一個(gè)Cursor對(duì)象,該Cursor對(duì)象包含了Content URI所關(guān)聯(lián)的文件的名稱和大小。默認(rèn)的實(shí)現(xiàn)返回下面兩列信息:

DISPLAY_NAME

文件名,String類型。這個(gè)值和File.getName()所返回的值一樣。

SIZE

文件大小,以字節(jié)為單位,long類型。這個(gè)值和File.length()所返回的值一樣。

客戶端應(yīng)用可以通過(guò)將query()的除了Content URI之外的其他參數(shù)都設(shè)置為“null”,來(lái)同時(shí)獲取文件的名稱(DISPLAY_NAME)和大小(SIZE)。例如,下面的代碼獲取一個(gè)文件的名稱大小,然后在兩個(gè)TextView中將他們顯示出來(lái):

    ...
    /*
     * Get the file's content URI from the incoming Intent,
     * then query the server app to get the file's display name
     * and size.
     */
    Uri returnUri = returnIntent.getData();
    Cursor returnCursor =
            getContentResolver().query(returnUri, null, null, null, null);
    /*
     * Get the column indexes of the data in the Cursor,
     * move to the first row in the Cursor, get the data,
     * and display it.
     */
    int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
    int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
    returnCursor.moveToFirst();
    TextView nameView = (TextView) findViewById(R.id.filename_text);
    TextView sizeView = (TextView) findViewById(R.id.filesize_text);
    nameView.setText(returnCursor.getString(nameIndex));
    sizeView.setText(Long.toString(returnCursor.getLong(sizeIndex)));
    ...


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)