Search code examples
androidandroid-studioandroid-file

Read text file after chossing by Intent.ACTION_GET_CONTENT


I'm trying to select text file by open file explorer then read the selected file. I tried many many solutions. the last one is this code

public void btnRead_Click(View view) {
    Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
    chooseFile.setType("text/plain");
    startActivityForResult(chooseFile, 1);
}

@Override
protected void onActivityResult(int requestedCode, int resultCode, Intent data) {

    if (requestedCode == 1) {
        if (resultCode == RESULT_OK) {

            File file = new File(data.getDataString());

            StringBuilder text = new StringBuilder();

            try {
                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){}

            textView = (TextView) findViewById(R.id.textView);
            textView.setText(text);

        }

    }
}

Thanks in advance


Solution

  • I found the solution here: https://stackoverflow.com/a/40638366/5727559

    The code is:

    public static int PICK_FILE = 1;
    
    public void btnRead_Click(View view)
    {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("text/plain");
        startActivityForResult(intent, PICK_FILE);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    
        if (requestCode == PICK_FILE)
        {
            if (resultCode == RESULT_OK)
            {
                Uri uri = data.getData();
                String fileContent = readTextFile(uri);
                Toast.makeText(this, fileContent, Toast.LENGTH_LONG).show();
            }
        }
    }
    
    private String readTextFile(Uri uri)
    {
        BufferedReader reader = null;
        StringBuilder builder = new StringBuilder();
        try
        {
            reader = new BufferedReader(new InputStreamReader(getContentResolver().openInputStream(uri)));
    
            String line = "";
            while ((line = reader.readLine()) != null)
            {
                builder.append(line);
            }
            reader.close();
        }
        catch (IOException e) {e.printStackTrace();}
        return builder.toString();
    }