如何从android中的.txt文件中获取String

时间:2016-11-16 16:18:40

标签: java android string file

我正在编写一个代码,该代码仅为.txt文件创建文件选择器,然后在String中表示其内容。问题是在选择文件后没有任何反应(日志表示结果代码为-1,请求代码为0)。谁能帮我?这是我对.txt文件的选择:

 public void onUploadClicked(View view) {
    Intent intent = new Intent();
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("text/plain");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, getText(R.string.select_file)), REQUEST_CODE);

}

这是我的OnActivityResult方法:

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

    if (resultCode == Activity.RESULT_OK) {
        if (data == null) {
            return;
        } else {
            Uri uri = data.getData();
            uploadedFile = new File(uri.getPath());
            try {
                readFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } else {
        return;
    }
}

这是我将.txt文件读入String:

的方法
private void readFile() throws IOException {

    uploadedString = new StringBuilder();
    BufferedReader reader = new BufferedReader(new FileReader(uploadedFile));
    String line;
    while ((line = reader.readLine()) != null) {

        uploadedString.append(line);
        uploadedString.append('\n');
    }
    Log.i("Uploaded successfully: ", uploadedString.toString());
    reader.close();
}

1 个答案:

答案 0 :(得分:5)

试试这个

PlayerHOC

然后覆盖public static int PICK_FILE = 1;

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

创建隐含意图

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