How To Get String From A .txt File In Android
I'm writing a code which creates a file chooser for only .txt files and then represents its contents in a String. The problem is that after selecting a file nothing happens (log sa
Solution 1:
Try this
publicstaticint PICK_FILE = 1;
Then overriding onActivityResult()
@OverrideprotectedvoidonActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FILE) {
if (resultCode == RESULT_OK) {
// User pick the fileUriuri= data.getData();
StringfileContent= readTextFile(uri);
Toast.makeText(this, fileContent, Toast.LENGTH_LONG).show();
} else {
Log.i(TAG, data.toString());
}
}
}
Method to read the text file picked by user
private String readTextFile(Uri uri){
BufferedReaderreader=null;
StringBuilderbuilder=newStringBuilder();
try {
reader = newBufferedReader(newInputStreamReader(getContentResolver().openInputStream(uri)));
Stringline="";
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return builder.toString();
}
Create an implicit intent
Intentintent=newIntent(Intent.ACTION_GET_CONTENT);
intent.setType("text/plain");
startActivityForResult(intent, PICK_FILE);
Post a Comment for "How To Get String From A .txt File In Android"