问题
The flow is:
- The user needs to select text file for use and the default Android explorer whatever pops up.
- Then I want to store string containing the file name, to actually open the file for reading.
- I want to open that file and rewrite him to new file on app internal storage.
- I want to open the new created file from app internal storage.
- Bonus 1 - If it's now
.txt
file but.doc
, I want to convert him to regular.txt
file in step 3 above of rewriting.
Bonus 2 - How to handle large text files?
Here's the code:
// 1. Start with user action pressing on button to select file
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, PICKFILE_RESULT_CODE);
}
});
// 2. Come back here
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICKFILE_RESULT_CODE) {
// Get the Uri of the selected file
Uri uri = data.getData();
String filePathName = "WHAT TODO ?";
LaterFunction(filePathName);
}
}
// 3. Later here
public void LaterFunction(String filePathName) {
BufferedReader br;
FileOutputStream os;
try {
br = new BufferedReader(new FileReader("WHAT TODO ?"));
//WHAT TODO ? Is this creates new file with
//the name NewFileName on internal app storage?
os = openFileOutput("newFileName", Context.MODE_PRIVATE);
String line = null;
while ((line = br.readLine()) != null) {
os.write(line.getBytes());
}
br.close();
os.close();
lastFunction("newFileName");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 4. And in the end here
public void lastFunction(String newFileName) {
//WHAT TODO? How to read line line the file
//now from internal app storage?
}
回答1:
Step #1: Delete String filePathName = "WHAT TODO ?";
Step #2: Change LaterFunction(filePathName);
to LaterFunction(uri);
Step #3: Change br = new BufferedReader(new FileReader("WHAT TODO ?"));
to br = new BufferedReader(new InputStreamReader(getContentResolver().openInputStream(uri));
That is the minimum necessary to address your question.
However, a MIME type of */*
will match any type of file, not just text files. Binary files should not be copied using readLine()
. If you only want plain text files, use text/plain
instead of */*
.
来源:https://stackoverflow.com/questions/29986553/android-open-text-file-to-read-after-intent-action-get-content