【Android Developers Training】 39. 获取文件信息

注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好。

原文链接:http://developer.android.com/training/secure-file-sharing/retrieve-info.html


当一个客户端应用尝试对一个有URI的文件进行操作时,应用可以向服务应用索取关于文件的信息,包括文件的数据类型和文件大小。数据类型可以帮助客户应用确定该文件自己能否处理,文件大小能帮助客户应用为文件设置合理的缓冲区。

这节课将展示如何通过查询服务应用的FileProvider来获取文件的MIME类型和尺寸。


一). 获取文件的MIME类型

一个文件的数据类型能够告知客户应用应该如何处理这个文件的内容。为了得到URI所对应文件的数据类型,客户应用调用ContentResolver.getType()。这个方法返回了文件的MIME类型。默认的,一个FileProvider通过文件的后缀名来确定其MIME类型。

下面的代码展示了一个客户应用如何在服务应用返回了文件的URI后,获得文件的MIME类型:

...
/*
* 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类有一个默认的query()方法的实现,它返回一个Cursor,它包含了URI所关联的文件的名字和尺寸。默认的实现返回两列:

DISPLAY_NAME

是文件的文件名,一个String。这个值和File.getName()所返回的值是一样的。

SIZE

文件的大小,字节为单位,一个“long”型。这个值和File.length()所返回的值是一样的。

客户端应用可以通过将query()的参数都设置为“null”,值保留URI这一参数,来同时获取文件的名字和尺寸。例如,下面的代码获取一个文件的名称和大小,然后在两个TextView中进行显示:

  ...
/*
* 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)));
...
上一篇:Python requests模块


下一篇:webpack学习笔记一