android 读取u盘指定路径的文件
时间: 2023-09-30 22:01:50 浏览: 171
您可以使用Android提供的Storage Access Framework (SAF) API来读取U盘中指定路径的文件。
以下是示例代码:
```java
// 在activity中启动SAF API
private static final int READ_REQUEST_CODE = 42;
public void openDocumentTree() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, READ_REQUEST_CODE);
}
// 处理SAF API回调
@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri treeUri = resultData.getData();
DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);
// 指定路径下的文件夹名称和文件名称
String folderName = "example_folder";
String fileName = "example_file.txt";
// 获取指定文件夹
DocumentFile folder = pickedDir.findFile(folderName);
if (folder != null && folder.isDirectory()) {
// 获取指定文件
DocumentFile file = folder.findFile(fileName);
if (file != null && file.isFile()) {
// 读取文件内容
try {
InputStream inputStream = getContentResolver().openInputStream(file.getUri());
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
}
String fileContent = stringBuilder.toString();
// 处理文件内容
// ...
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
```
注意:您需要在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
```
阅读全文