3

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" />
user3441466
  • 43
  • 1
  • 6

3 Answers3

0

if you are running on or above lollipop you need to ask permissions in java code. check out this link https://stackoverflow.com/a/33162451/7457753

Community
  • 1
  • 1
AKSHAY MANAGOOLI
  • 120
  • 2
  • 2
  • 21
0
/dev/bus/001/002/a.txt. 

That is an impossible non existend file system path. Which File:exists() already told you. You should return then and stop with your code. Now you continue as if nothing has happened.

You better had asked or googled 'how to determine path to usb pen drive'.

Well have a look at second or third item returned by getExternalFilesDirs().

You are sure your device supports OTG?

greenapps
  • 11,154
  • 2
  • 16
  • 19
  • I try getExternalFilesDirs() and not work, my device support OTG – user3441466 Apr 19 '17 at 04:13
  • Please tell us the paths you get from getExternalFilesDirs() for both devices. Tell if you use a micro SD card in them. It would be nice if you showed the used code. – greenapps Apr 19 '17 at 07:02
0

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

user3441466
  • 43
  • 1
  • 6