问题
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