Search code examples
androidusbusb-otg

read file from usb removable storage


in my application I want to read a file from usb removable storage I have a.txt and i want to read it

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();
    }
}
}

when check file exists return false and when opening and reading file throw exception

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

in Manifest have

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

Solution

  • none of this solution worked for me I searched and found this library

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

    tested and worked for me