如何从android中的文件路径读取文件的所有内容?

时间:2014-04-15 05:30:15

标签: android filepath

我正在获取文件路径。如何获取文件内容。然后我需要发送到JavaScript。 我需要string或stringbuilder中的所有数据,以便我可以发送javascipt.can你请告诉我如何阅读带路径的文件内容

 ------------------FilePath------------------/storage/sdcard0/Download/a.txt

 @Override  
 protected void onActivityResult(int requestCode, int resultCode,  
                                    Intent intent) {  

      if (requestCode == FILECHOOSER_RESULTCODE) {

            if (mUploadMessage == null)
                return;

            Uri result = intent == null || resultCode != RESULT_OK ? null
                    : intent.getData();
            if (result!=null){

                String filePath = null;

                if ("content".equals(result.getScheme())) {

                    Cursor cursor = this.getContentResolver().query(result, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
                        cursor.moveToFirst();   
                        filePath = cursor.getString(0);
                        cursor.close();

                } else {


                    filePath = result.getPath();
                    System.out.println("------------------FilePath------------------"+filePath);
                    // content send to java script
                  //String msgToSend = Msg.getText().toString();
                    //  web.loadUrl("javascript:loadData(\""+msgToSend+"\")");
                    //  web.loadUrl("javascript:loadData()");
                        filePath = result.getPath();

                }

                Uri myUri = Uri.parse(filePath);
                mUploadMessage.onReceiveValue(myUri);

            } else {

                mUploadMessage.onReceiveValue(result);

            }

            mUploadMessage = null;
        }
  }  

1 个答案:

答案 0 :(得分:0)

如果您有filePath,可以尝试以下内容:

File file = new File(filePath);


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');
    }
}
catch (IOException e) {
    //Exception-handling
}