read file from usb removable storage

痞子三分冷 提交于 2019-12-11 05:58:07

问题


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

回答1:


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




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/43465772/read-file-from-usb-removable-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!