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 sobre el archivo desde la app de servidor, incluido el tipo de datos y el tamaño del archivo. El tipo de datos ayuda a la app cliente a determinar si puede procesar el archivo, y el tamaño del archivo la ayuda a configurar el almacenamiento en búfer y en caché del archivo.

En esta lección, se muestra cómo consultar el objeto FileProvider del servidor de la app 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 según el URI de contenido, la aplicación 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 de nombre del archivo.

En el siguiente fragmento de código, se observa cómo una app cliente obtiene el tipo de MIME de un archivo después de que la app del servidor muestra 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 a un URI de contenido en un Cursor. La implementación predeterminada muestra dos columnas:

DISPLAY_NAME
El nombre del archivo, como String. El valor es el mismo que muestra File.getName().
SIZE
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 de un archivo si configuras todos los argumentos de query() como null, excepto el URI de contenido. Por ejemplo, este fragmento de código recupera DISPLAY_NAME y SIZE de un archivo, y muestra cada uno en una TextView distinta:

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: