Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

{Android} How can I open my text file from uri?

Tags:

text

android

uri

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

like image 923
Trabefi Avatar asked Oct 17 '25 17:10

Trabefi


1 Answers

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());
    }
}
like image 130
Trabefi Avatar answered Oct 20 '25 06:10

Trabefi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!