Android open text file to read after Intent.ACTION_GET_CONTENT

倖福魔咒の 提交于 2020-01-30 06:50:08

问题


The flow is:

  1. The user needs to select text file for use and the default Android explorer whatever pops up.
  2. Then I want to store string containing the file name, to actually open the file for reading.
  3. I want to open that file and rewrite him to new file on app internal storage.
  4. I want to open the new created file from app internal storage.
  5. 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

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