Подтвердить что ты не робот

Как прочитать содержимое файла из внутреннего хранилища - приложение для Android

Я новичок, работающий с Android. Файл уже создан в местоположении data/data/myapp/files/hello.txt; содержимое этого файла "привет". Как читать содержимое файла?

4b9b3361

Ответ 1

Посмотрите, как использовать хранилища в Android http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

Для чтения данных из внутреннего хранилища вам нужна папка с файлами приложений и отсюда содержимое

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

Также вы можете использовать этот подход

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);
}

Ответ 2

Прочитайте файл как полную версию строки (обработка исключений с использованием UTF-8, обработка новой строки):

// 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 "";
        }
    }

Примечание. Вам не нужно беспокоиться о пути к файлу только с именем файла.

Ответ 3

Вызов Для следующей функции с аргументом в качестве пути к файлу:

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;
}

Ответ 4

    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());

    }

Ответ 5

Чтобы прочитать файл из внутреннего хранилища:

Вызвать openFileInput() и передать ему имя файла для чтения. Эта возвращает FileInputStream. Прочитайте байты из файла с помощью read(). затем закройте поток с помощью close().

код::

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();

Ответ 6

Я предпочитаю использовать 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) {}

Ответ 7

Для других, которые ищут ответ на вопрос, почему файл не читается, особенно на SD-карте, напишите файл следующим образом. Обратите внимание на 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;
        }