从 USB 可移动存储读取文件

read file from usb removable storage

在我的应用程序中,我想从 USB 可移动存储中读取一个文件 我有 a.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();
    }
}
}

当检查文件存在时return false 并且当打开和读取文件时抛出异常

java.io.filenotfoundexception :/dev/bus/001/002/a.txt: opent failed : EACCES (permission denied)

清单中有

<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" />

如果您 运行 在棒棒糖上或以上,您需要在 java 代码中请求权限。 看看这个 link

/dev/bus/001/002/a.txt. 

这是一个不可能的不存在的文件系统路径。 File:exists() 已经告诉你了。然后你应该 return 然后停止你的代码。现在你继续,就好像什么都没有发生过一样。

你最好问过或用谷歌搜索过 'how to determine path to usb pen drive'。

我们来看看 getExternalFilesDirs() 编辑的第二或第三项 return。

您确定您的设备支持OTG吗?

none 这个解决方案对我有用 我搜索并找到了这个图书馆

Open source library to access USB Mass Storage devices on Android without rooting your device

测试并为我工作