2015-11-13 99 views
2

我从存储中选择了一个文本文件并获取了它的路径(FilePath),我试图读取该文本文件的内容并将其放入edittext ..我使用下面的代码获取文本文件数据,并把它的EditText(eTPronounce)选择文本文件并阅读Android

File sdcard = Environment.getExternalStorageDirectory(); 


//Get the text filea 
       File file = new File(sdcard,FilePath); 

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

//Find the view by its i 

//Set the text 
      eTPronounce.setText(text); 

      } 
     }); 

如果我和那里是文本文件,其works.For例如,如果我有“下载/文本替换filepath任何目录替换filepath(在第二行)。 TXT“它的工作原理。 我以前this链接来获取文件路径

THANKS

+0

全码http://jpst.it/D5an –

+0

你添加使用许可权 –

+0

如果读比什么是问题,我想你应该检查文件是否存在该文件第一不是试图阅读它 –

回答

1

,我认为你应该使用下面的构造

File(File dir, String name) 

,或者您可以使用

File(String path) 

如果指定目录名,您只需按照第一个示例中所示提供文件名称。否则,您可以使用第二个文件与完整文件pat^h

+0

所以我应该替换这个文件file = new File(sdcard,FilePath);与此文件file =新文件(字符串,FilePath); –

+0

不使用新文件(FilePath)。 我认为,filepath是文件 –

+0

Brooooooooooooooooooo的完整路径,我爱你thankssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss –

1
if(resultCode==RESULT_OK){ 
    if(data == null || data.getData == null){ 
     //Log.e() 
     return; 
    } 
FilePath = getPath(data.getData(),mActivity); 
setfilename.setText(FilePath); 
} 

    public static String getPath(Uri uri,Context ctx) { 
     String res = null; 
     if(null==uri){ 
      return res; 
     } 
     if (uri != null && uri.toString().startsWith("file://")) { 
      return uri.toString().substring("file://".length()); 
     } 
     String[] proj = { MediaStore.Images.Media.DATA }; 
     Cursor cursor = ctx.getContentResolver().query(uri, proj, null, null, null); 
     if(cursor!=null){ 
      if(cursor.moveToFirst()){ 
       try { 
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
        res = cursor.getString(column_index); 
       }catch (Exception ignored){ 
       }finally { 
        closeCursor(cursor); 
       } 
      } 
     } 
     closeCursor(cursor); 
     return res; 
    } 
+0

感谢您的帮助! –

+0

不客气。 –