Android打开文件获取文件内容
时间: 2024-02-24 17:59:00 浏览: 17
要在Android中打开文件并获取文件内容,您可以使用以下代码:
```java
// 选择文件
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, 1);
// 获取文件内容
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
Uri uri = data.getData();
String filePath = uri.getPath();
try {
File file = new File(filePath);
FileInputStream inputStream = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
String fileContent = stringBuilder.toString();
// 处理文件内容
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这段代码使用 `Intent.ACTION_GET_CONTENT` 打开文件选择器,让用户选择要打开的文件。然后,通过读取文件内容的方式获取文件内容。