Android open text file to read after Intent.ACTION_GET_CONTENT

前端 未结 2 1432
野性不改
野性不改 2021-01-20 13:14

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
相关标签:
2条回答
  • 2021-01-20 13:56

    For those who struggle to fix that code here is the fixed one

    ab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("*/*");
                    startActivityForResult(intent, PICKFILE_RESULT_CODE);
                }
            });
    
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == PICKFILE_RESULT_CODE) {
                Uri uri = data.getData();
                LaterFunction(uri);
            }
        }
    
    public void LaterFunction(Uri uri) {
            BufferedReader br;
            FileOutputStream os;
            try {
                br = new BufferedReader(new InputStreamReader(getContentResolver().openInputStream(uri)));
                //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());
                    Log.w("nlllllllllllll",line);
                }
                br.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    0 讨论(0)
  • 2021-01-20 14:02

    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 */*.

    0 讨论(0)
提交回复
热议问题