4

I want to create an app that will be capable of opening text files from uri. At the time, I have this code:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.text_view_layout);
    final Uri uri = getIntent() != null ? getIntent().getData() : null;
    StringBuilder text = new StringBuilder();
    InputStream inputStream = null;

}

how can I make it read the whole file ? Best regards, Traabefi

Lukáš Anda
  • 560
  • 1
  • 5
  • 23

2 Answers2

6

I've done some magic with this and it's working very good :D Here is my code:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.text_view_layout);
    final Uri uri = getIntent() != null ? getIntent().getData() : null;
    InputStream inputStream = null;
    String str = "";
    StringBuffer buf = new StringBuffer();
    TextView txt = (TextView)findViewById(R.id.textView);
    try {
        inputStream = getContentResolver().openInputStream(uri);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    if (inputStream!=null){
        try {
            while((str = reader.readLine())!=null){
                buf.append(str+"\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        txt.setText(buf.toString());
    }
}
Lukáš Anda
  • 560
  • 1
  • 5
  • 23
3

Create a new File object from Uri's path and pass it to the FileInputStream constructor:

try {
    inputStream = new FileInputStream(new File(uri.getPath()));
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

Scanner s = new Scanner(inputStream).useDelimiter("\\A");
yourTextView.setText(s.hasNext() ? s.next() : "");

I got the InputStream to String technique from this answer by Pavel Repin.

Don't forget to close your stream.

Community
  • 1
  • 1
Voicu
  • 16,921
  • 10
  • 60
  • 69