【问题标题】:How to find the path of USB which is mounted to android?如何找到安装到android的USB路径?
【发布时间】:2013-04-28 12:24:36
【问题描述】:

我正在开发一个从 USB 读取数据的 android 应用程序。 USB可以通过串口连接到android,我的应用程序可以找到它。

现在,我想从 USB 读取数据文件和文件夹。我读过很多文章。我发现他们使用了这段代码:

Environment.getExternalStorageDirectory();

但就我而言,我知道路径是 /storage/emulated/0。 当我尝试读取路径中包含的所有文件时,我得到以下语句:

/storage/emulated/0/Android
/storage/emulated/0/Music
/storage/emulated/0/Podcasts
/storage/emulated/0/Ringtones

等等

但找不到我的 USB 路径。所以,我不确定它是从 USB 读取文件的正确方法吗?

这是我的代码:

File f = Environment.getExternalStorageDirectory();
File[] files = f.listFiles();
String fol = "";
for (File inFile : files) {
    if (inFile.isDirectory()) {
        fol += inFile.toString()+"\n";
    }
}
TextView tv = (TextView) findViewById(R.id.demoTitle);
tv.setText(fol);

【问题讨论】:

    标签: android usbserial usb-flash-drive


    【解决方案1】:

    使用此代码获取所有已安装的设备

    public String getStoragepath() {
        try {
            Runtime runtime = Runtime.getRuntime();
            Process proc = runtime.exec("mount");
            InputStream is = proc.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            String line;
            String[] patharray = new String[10];
            int i = 0;
            int available = 0;
    
            BufferedReader br = new BufferedReader(isr);
            while ((line = br.readLine()) != null) {
                String mount = new String();
                if (line.contains("secure"))
                    continue;
                if (line.contains("asec"))
                    continue;
    
                if (line.contains("fat")) {// TF card
                    String columns[] = line.split(" ");
                    if (columns != null && columns.length > 1) {
                        mount = mount.concat(columns[1] + "/requiredfiles");
    
                        patharray[i] = mount;
                        i++;
    
                        // check directory is exist or not
                        File dir = new File(mount);
                        if (dir.exists() && dir.isDirectory()) {
                            // do something here
    
                            available = 1;
                            finalpath = mount;
                            break;
                        } else {
    
                        }
                    }
                }
            }
            if (available == 1) {
    
            } else if (available == 0) {
                finalpath = patharray[0];
            }
    
        } catch (Exception e) {
    
        }
        return finalpath;
    }
    

    【讨论】:

    • 感谢代码,我将其用作后备,我首先检查文件“proc/mounts”是否存在并读取它,如果不存在,则通过此脚本读取它。
    • 我们不应该依赖“fat”或“vfat”新设备有时将“fuse”作为分区类型,它的大脚本检测分区,但它们以“/dev/”开头并且可能是vfat或熔断,并且您可能有相同分区的重复路径,请注意这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多