Cómo recuperar información de archivos

Antes de que una app cliente intente trabajar con un archivo para el que tiene un URI de contenido, puede solicitar información acerca del archivo desde la app de servidor, incluidos el tipo de datos y el tamaño del archivo. El tipo de datos ayuda a la app cliente a determinar si puede controlar el archivo, y el tamaño del archivo ayuda a la app cliente a configurar el almacenamiento en búfer y el almacenamiento en caché para el archivo.

En esta lección, se muestra cómo consultar el objeto FileProvider de la app de servidor para obtener el tipo y el tamaño de MIME de un archivo.

Cómo obtener el tipo de MIME de un archivo

El tipo de datos de un archivo indica a la app cliente cómo procesar el contenido del archivo. Para obtener el tipo de datos de un archivo compartido a partir de su URI de contenido, la app cliente llama a ContentResolver.getType(). Este método muestra el tipo de MIME del archivo. De forma predeterminada, un FileProvider determina el tipo de MIME del archivo a partir de la extensión del nombre del archivo.

En el siguiente fragmento de código, se muestra cómo una app cliente recupera el tipo de MIME de un archivo una vez que la app de servidor devuelve el URI de contenido al cliente:

Kotlin

    ...
    /*
     * Get the file's content URI from the incoming Intent, then
     * get the file's MIME type
     */
    val mimeType: String? = returnIntent.data?.let { returnUri ->
        contentResolver.getType(returnUri)
    }
    ...

Java

    ...
    /*
     * 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);
    ...

Cómo obtener el nombre y el tamaño de un archivo

La clase FileProvider tiene una implementación predeterminada del método query() que muestra el nombre y el tamaño del archivo asociado con un URI de contenido en un Cursor. La implementación predeterminada muestra dos columnas:

DISPLAY_NAME
Corresponde al nombre del archivo, como String. Este valor es el mismo que muestra File.getName().
SIZE
Es el tamaño del archivo en bytes, como long. Este valor es el mismo que el que muestra File.length().

La app cliente puede obtener DISPLAY_NAME y SIZE para un archivo si configura todos los argumentos de query() como null, excepto el URI de contenido. Por ejemplo, este fragmento de código recupera los elementos DISPLAY_NAME y SIZE de un archivo, y muestra cada uno en TextView por separado:

Kotlin

    /*
     * Get the file's content URI from the incoming Intent,
     * then query the server app to get the file's display name
     * and size.
     */
    returnIntent.data?.let { returnUri ->
        contentResolver.query(returnUri, null, null, null, null)
    }?.use { cursor ->
        /*
         * Get the column indexes of the data in the Cursor,
         * move to the first row in the Cursor, get the data,
         * and display it.
         */
        val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
        val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE)
        cursor.moveToFirst()
        findViewById<TextView>(R.id.filename_text).text = cursor.getString(nameIndex)
        findViewById<TextView>(R.id.filesize_text).text = cursor.getLong(sizeIndex).toString()
        ...
    }

Java

    ...
    /*
     * 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)));
    ...

Para obtener información adicional relacionada, consulta: