How to open a .txt file from internal storage in a textview on Android studio? [duplicate]

不问归期 提交于 2019-12-24 19:36:07

问题


trying to open a simple .txt file from the file explorer into textview, why this is so hard ?

I think the problem is on the path, for some reason I can't get the right path when I use the file explorer.

This is what I tried :

        txtFile.setOnClickListener( new View.OnClickListener() {
         @Override
        public void onClick(View view) { 
            Intent txtIntent ;
            txtIntent = new Intent();
            txtIntent .setAction( Intent.ACTION_GET_CONTENT );
            txtIntent .setType( "*/*" );
            startActivityForResult( Intent.createChooser( txtIntent , "DEMO" ), 1001 );

    }
    } );




     public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult( requestCode, resultCode, data );
            String path = data.getData().getPath();
            // path = path.replace("document/primary:", "storage/emulated/0/"); // this can open files from internal storage but don't works with external storage or from "Recent" shortcut or "Downloads" shortcut.
            tv.setText( path );
            System.out.println( path );


            StringBuilder text = new StringBuilder();
            try {
                File file = new File(path);
                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) {
                e.printStackTrace();
                Toast.makeText( getApplicationContext(), "Error reading file!", Toast.LENGTH_LONG ).show();
            }

            TextView test = (TextView)findViewById(R.id.test);
            test.setText(text.toString());
}

Sorry for my poor English. thx

来源:https://stackoverflow.com/questions/59167642/how-to-open-a-txt-file-from-internal-storage-in-a-textview-on-android-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!