如何从内部存储 - Android应用程序中读取文件内容

时间:2013-02-08 08:06:48

标签: android internal

我是使用Android的新手。已在位置data/data/myapp/files/hello.txt中创建文件;这个文件的内容是“你好”。我如何阅读文件的内容?

7 个答案:

答案 0 :(得分:56)

看看如何在android http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

中使用存储

要从内部存储中读取数据,您需要使用app文件夹并从此处阅读内容

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

答案 1 :(得分:7)

以字符串完整版本的形式读取文件(使用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 "";
        }
    }

注意:您不需要仅使用文件名来处理文件路径。

答案 2 :(得分: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;
}

答案 3 :(得分:1)

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

    }

答案 4 :(得分:0)

从内部存储中读取文件:

  

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

答案 5 :(得分:0)

我更喜欢使用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) {}

答案 6 :(得分:-1)

对于其他寻找文件无法读取的原因的答案,特别是在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;
        }