gpt4 book ai didi

android - 从 USB 可移动存储读取文件

转载 作者:行者123 更新时间:2023-12-05 07:43:43 26 4
gpt4 key购买 nike

在我的应用程序中,我想从 usb 可移动存储中读取一个文件我有一个.txt,我想阅读它

void read() {
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
StringBuffer sb = new StringBuffer();
while (deviceIterator.hasNext()) {
UsbDevice device = deviceIterator.next();
String Model = device.getDeviceName();

try {
File file = new File(Model + "/a.txt");
if (file.exists())
Toast.makeText(getApplicationContext(), "Exist", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "Not Exist", Toast.LENGTH_LONG).show();

BufferedReader br = new BufferedReader(new FileReader(Model + "/a.txt"));
String sCurrentLine;

while ((sCurrentLine = br.readLine()) != null) {
textView.append(sCurrentLine + "\n");
}

} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}

检查文件存在时返回false,打开读取文件时抛出异常

java.io.filenotfoundexception :/dev/bus/001/002/a.txt: 打开失败:EACCES(权限被拒绝)

在Manifest中有

<uses-permission android:name="android.permission.USB_PERMISSION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_MEDIA_STORAGE" />

最佳答案

如果您在 Lollipop 之上或之上运行,您需要在 Java 代码中请求权限。查看此链接 https://stackoverflow.com/a/33162451/7457753

关于android - 从 USB 可移动存储读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43465772/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com