47

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

4

7 回答 7

66

看看如何在 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);
}
于 2013-02-08T08:19:23.757 回答
10

将文件作为字符串完整版本读取(处理异常,使用 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 "";
        }
    }

注意:您不需要只关心文件名的文件路径。

于 2014-01-06T21:02:18.457 回答
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;
}
于 2013-02-08T08:19:38.750 回答
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();
于 2013-02-08T08:23:15.423 回答
0
    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());

    }
于 2016-07-27T12:55:50.480 回答
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) {}
于 2018-06-20T07:38:17.533 回答
-1

对于寻找文件不可读的答案的其他人,尤其是在 sdcard 上,请先像这样编写文件。注意 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;
        }
于 2014-04-02T14:17:19.357 回答