项目开发过程中, 有导出excel文件到u盘的需求, 但是使用的android5.1系统u盘没有挂载, 导致数据无法导出。
解决方式如下:
String folder = "/system/etc/usb_tmp";
String filePath = folder+"/excel.xls";
try {
//创建临时文件夹usb_tmp
Process su = Runtime.getRuntime().exec("/system/xbin/su");
String cmd = "mkdir "+folder+"n" +"chmod 777 "+folder +"nexitn";
Log.d("", "mkdir:usb_tmp n"+cmd);
su.getOutputStream().write(cmd.getBytes());
if(su.waitFor()!=0){
Log.d("", "mkdir:usb_tmp: false ");
flag = false;
}
//文件导出到usb_tmp
File file = new File(filePath);
OutputStream outputStream= new FileOutputStream(file);
//自定义类ExportExcel excel文件导出
ExportExcel.exportExcel(outputStream,list);
} catch (Exception e) {
e.printStackTrace();
flag = false;
}
int count = 0;
try {
//u盘插入硬件位置/dev/block/sd* 可以通过adb shell查看
File dFolder = new File("/dev/block");
File[] files = dFolder.listFiles();
for(File file : files){
if(file.getName().startsWith("sd")){
count++;
String mountPath = "/system/etc/usb_"+count;
//创建临时文件夹mountPath; u盘挂载在mountPath上; 复制excel文件到u盘; umount mountPath; 删除mountPath
Process su = Runtime.getRuntime().exec("/system/xbin/su");
String cmd = "mkdir "+mountPath+"n" +"chmod 777 "+mountPath + "nmount -t vfat "+file.getAbsolutePath()+" "+mountPath+"ncp "+filePath+" "+mountPath+"numount "+mountPath+"nrm -r "+mountPath+"nexitn";
Log.d("", "mount_copy_umount n"+cmd);
su.getOutputStream().write(cmd.getBytes());
if(su.waitFor()!=0){
flag = false;
Log.d("", "mount_copy_umount: false");
}
}
}
} catch (Exception e) {
e.printStackTrace();
flag = false;
}
try {
//删除usb_tmp
Process su = Runtime.getRuntime().exec("/system/xbin/su");
String cmd = "rm -r "+folder+"nexitn";
su.getOutputStream().write(cmd.getBytes());
if(su.waitFor()!=0){
Log.d("", "rm -r usb_tmp: false ");
flag = false;
}
} catch (Exception e) {
e.printStackTrace();
flag = false;
}
if(flag && count>0){
showToast("数据已保存至u盘");
}else {
showToast("数据保存至U盘失败,请确认U盘已挂载");
}



