U盘插入系统之后,如果系统检测到U盘,便会在系统的proc目录的mounts文件内产生一条记录。如下:
rootfs / rootfs ro,relatime 0 0
tmpfs /dev tmpfs rw,seclabel,nosuid,relatime,mode=755 0 0
devpts /dev/pts devpts rw,seclabel,relatime,mode=600 0 0
proc /proc proc rw,relatime 0 0
sysfs /sys sysfs rw,seclabel,relatime 0 0
selinuxfs /sys/fs/selinux selinuxfs rw,relatime 0 0
none /acct cgroup rw,relatime,cpuacct 0 0
none /sys/fs/cgroup tmpfs rw,seclabel,relatime,mode=750,gid=1000 0 0
tmpfs /mnt/secure tmpfs rw,seclabel,relatime,mode=700 0 0
tmpfs /mnt/asec tmpfs rw,seclabel,relatime,mode=755,gid=1000 0 0
tmpfs /mnt/obb tmpfs rw,seclabel,relatime,mode=755,gid=1000 0 0
none /dev/cpuctl cgroup rw,relatime,cpu 0 0
debugfs /sys/kernel/debug debugfs rw,relatime 0 0
/dev/block/by-name/system /system ext4 ro,seclabel,relatime,data=ordered 0 0
/dev/block/by-name/cache /cache ext4 rw,seclabel,nosuid,nodev,noatime,nomblk_io_submit,data=ordered 0 0
/dev/block/by-name/UDISK /data ext4 rw,seclabel,nosuid,nodev,noatime,nomblk_io_submit,noauto_da_alloc,data=ordered 0 0
/dev/fuse /mnt/shell/emulated fuse rw,nosuid,nodev,relatime,user_id=1023,group_id=1023,default_permissions,allow_other 0 0
tmpfs /mnt/usbhost1 tmpfs rw,seclabel,nosuid,nodev,relatime,uid=1023,gid=1023 0 0
/dev/block/vold/8:4 /mnt/usbhost1/8_4 vfat rw,dirsync,nosuid,nodev,noexec,relatime,uid=1023,gid=1023,fmask=0007,dmask=0007,allow_utime=0020,codepage=cp437,iocharset=ascii,shortname=mixed,utf8,errors=remount-ro 0 0
/dev/fuse /storage/usbhost1 fuse rw,nosuid,nodev,relatime,user_id=1023,group_id=1023,default_permissions,allow_other 0 0
其中,/mnt/usbhost1/8_4 就是U盘的挂载路径。我们只需要把 /proc/mounts 文件内的带 vfat 的最后一行找到,截取其中的 U 盘路径即可。代码如下:
private void searchPath() {
String filePath = "/proc/mounts";
File file = new File(filePath);
List<String> lineList = new ArrayList<>();
InputStream inputStream =null;
try {
inputStream = new FileInputStream(file);
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "GBK");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = "";
while ((line = bufferedReader.readLine()) != null) {
if (line.contains("vfat")) {
lineList.add(line);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String editPath = lineList.get(lineList.size() - 1);
int start = editPath.indexOf("/mnt");
int end = editPath.indexOf(" vfat");
String path = editPath.substring(start, end);
Log.d("SelectBusLineDialog", "path: " + path);
}