开启选择页面
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");//筛选器
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent,"选择一个文件"),1);
读取选择的文件中的内容(这里是读取的文本文件)
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (resultCode == Activity.RESULT_OK) {
try {
//保存读取到的内容
StringBuilder result = new StringBuilder();
//获取URI
Uri uri = data.getData();
//获取输入流
InputStream is = getContext().getContentResolver().openInputStream(uri);
//创建用于字符输入流中读取文本的bufferReader对象
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
//将读取到的内容放入结果字符串
result.append(line);
}
//文件中的内容
String content = result.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|