Cómo leo el contenido del archivo desde el almacenamiento interno-Android App


Soy un novato que trabaja con Android. Un archivo ya está creado en la ubicación data/data/myapp/files/hello.txt; el contenido de este archivo es "hola". ¿Cómo leo el contenido del archivo?

Author: newenglander, 2013-02-08

7 answers

Echa un vistazo a esto cómo usar almacenamientos en android http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

Para leer los datos del almacenamiento interno, necesita la carpeta de archivos de la aplicación y leer el contenido desde aquí

String yourFilePath = context.getFilesDir() + "/" + "hello.txt";

File yourFile = new File( yourFilePath );

También puede utilizar este enfoque

   FileInputStream fis = context.openFileInput("hello.txt");
   InputStreamReader isr = new InputStreamReader(fis);
   BufferedReader bufferedReader = new BufferedReader(isr);
   StringBuilder sb = new StringBuilder();
   String line;
   while ((line = bufferedReader.readLine()) != null) {
       sb.append(line);
   }
 47
Author: Georgy Gobozov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-06 16:58:31

Lee un archivo como una cadena versión completa (manejando excepciones, usando UTF-8, manejando nueva línea):

// Calling:
/* 
    Context context = getApplicationContext();
    String filename = "log.txt";
    String str = read_file(context, filename);
*/  
public String read_file(Context context, String filename) {
        try {
            FileInputStream fis = context.openFileInput(filename);
            InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            return sb.toString();
        } catch (FileNotFoundException e) {
            return "";
        } catch (UnsupportedEncodingException e) {
            return "";
        } catch (IOException e) {
            return "";
        }
    }

Nota: no necesita preocuparse por la ruta del archivo solo con el nombre del archivo.

 6
Author: Skalár Wag,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-06 21:02:18

Llame a la siguiente función con el argumento como ruta del archivo:

private String getFileContent(String targetFilePath){
           File file = new File(targetFilePath);
           try {
                    fileInputStream = new FileInputStream(file);
           }
           } catch (FileNotFoundException e) {
                  // TODO Auto-generated catch block
                  Log.e("",""+e.printStackTrace());
           }
           StringBuilder sb;
           while(fileInputStream.available() > 0) {

                 if(null== sb)  sb = new StringBuilder();

            sb.append((char)fileInputStream.read());
           }
       String fileContent;
       if(null!=sb){
            fileContent= sb.toString();
            // This is your fileContent in String.


       }
       try {
          fileInputStream.close();
       }
       catch(Exception e){
           // TODO Auto-generated catch block
           Log.e("",""+e.printStackTrace());
       }
           return fileContent;
}
 3
Author: shridutt kothari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-08 08:19:38
    String path = Environment.getExternalStorageDirectory().toString();
    Log.d("Files", "Path: " + path);
    File f = new File(path);
    File file[] = f.listFiles();
    Log.d("Files", "Size: " + file.length);
    for (int i = 0; i < file.length; i++) {
        //here populate your listview
        Log.d("Files", "FileName:" + file[i].getName());

    }
 1
Author: Dmarp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-27 12:55:50

Para leer un archivo desde el almacenamiento interno:

Llamar openFileInput() y pasarle el nombre del archivo a leer. Este devuelve un FileInputStream. Leer bytes del archivo con read (). Entonces cierra la secuencia con close().

Código::

StringBuilder sb = new StringBuilder();
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            is.close();
        } catch(OutOfMemoryError om){
            om.printStackTrace();
        } catch(Exception ex){
            ex.printStackTrace();
        }
        String result = sb.toString();
 0
Author: jlopez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-08 08:23:15

Prefiero usar java.util.Scanner:

try {
    Scanner scanner = new Scanner(context.openFileInput(filename)).useDelimiter("\\Z");
    StringBuilder sb = new StringBuilder();

    while (scanner.hasNext()) {
        sb.append(scanner.next());
    }

    scanner.close();

    String result = sb.toString();

} catch (IOException e) {}
 0
Author: Hafez Divandari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-20 17:29:53

Para otros que buscan una respuesta a por qué un archivo no es legible especialmente en una tarjeta SD, escriba el archivo de esta manera primero.. Observe el MODE_WORLD_READABLE

try {
            FileOutputStream fos = Main.this.openFileOutput("exported_data.csv", MODE_WORLD_READABLE);
            fos.write(csv.getBytes());
            fos.close();
            File file = Main.this.getFileStreamPath("exported_data.csv");
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
 -1
Author: DagW,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-27 07:36:22