从Android内部存储器上的.txt文件中读取文本作为字符串

时间:2015-10-22 16:45:04

标签: android android-intent service broadcastreceiver

我想将Android内部存储空间中的.txt文件读取为string变量。

但是当我尝试加载字符串时,我收到了这个错误:

Cannot convert multipart to String

1 个答案:

答案 0 :(得分:1)

我假设你的android的“内部存储”中有一个.txt文件

内部存储空间

中读取文件
  

调用openFileInput()并将其传递给要读取的文件的名称。这个   返回一个FileInputStream。使用read()从文件中读取字节。然后   用close()关闭流。

   FileInputStream fis = context.openFileInput("test.txt", Context.MODE_PRIVATE);
   InputStreamReader isr = new InputStreamReader(fis);
   BufferedReader bufferedReader = new BufferedReader(isr);
   StringBuilder sb = new StringBuilder();
   String line;
   while ((line = bufferedReader.readLine()) != null) {
       sb.append(line);
   }
   bufferedReader.close(); 

如果您的文件位于 SD卡

//Find the directory for the SD Card
File sdcard = Environment.getExternalStorageDirectory();

//Get the text file 
File file = new File(sdcard,"test.txt");

//Read text from file 
StringBuilder text = new StringBuilder();

try { 
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;

    while ((line = br.readLine()) != null) {
        text.append(line);
        text.append('\n');
    } 
    br.close();
} 
catch (IOException e) {
    //You'll need to add proper error handling here 
}