通过Intent选择后读取文本文件。ACTION_GET_CONTENT

时间:2018-10-10 20:08:36

标签: android android-studio android-file

我正在尝试通过打开文件浏览器选择文本文件,然后读取所选文件。 我尝试了许多解决方案。最后一个是这段代码

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);

        }

    }
}

预先感谢

1 个答案:

答案 0 :(得分:0)

我在这里找到了解决方法:https://stackoverflow.com/a/40638366/5727559

代码是:

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();
}