Skip to content Skip to sidebar Skip to footer

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

public static int PICK_FILE = 1;

Then overriding onActivityResult()

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_FILE) {
            if (resultCode == RESULT_OK) {
                // User pick the file
                Uri uri = data.getData();
                String fileContent = 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){
        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);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return builder.toString();
    }

Create an implicit intent

Intent intent = new Intent(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"