@Tyhj
2018-05-12T11:54:08.000000Z
字数 1584
阅读 3294
Android
https://www.zybuluo.com/Tyhj/note/1144629
最近工作中遇到数据从U盘导出的功能,网上找了一下,有个开源的框架可以拿来使用,U盘和内存卡什么的不一样,是用OTG口来连接手机的,有些手机不支持,有些手机支持,U盘格式也有几种,常见的exFAT、FAT32、NTFS,有些手机可能不支持所有格式的U盘,
//导入依赖:compile 'com.github.mjdev:libaums:0.5.5'
//获取到OTG连接的U盘public static FileSystem otgGet(Context context) {UsbMassStorageDevice[] devices = UsbMassStorageDevice.getMassStorageDevices(context);FileSystem currentFs = null;for (UsbMassStorageDevice device : devices) {//一般只有一个OTG借口,所以这里只取第一个try {device.init();//如果设备不支持一些格式的U盘,这里会有异常if (device == null || device.getPartitions() == null ||device.getPartitions().get(0) == null ||device.getPartitions().get(0).getFileSystem() == null) {return null;}currentFs = device.getPartitions().get(0).getFileSystem();Log.e("OTG", "容量: " + currentFs.getCapacity());Log.e("OTG", "已使用空间: " + currentFs.getOccupiedSpace());Log.e("OTG", "剩余空间: " + currentFs.getFreeSpace());Log.e("OTG", "block数目: " + currentFs.getChunkSize());} catch (Exception e) {return null;}}return currentFs;}
//获取根目录UsbFile root = fileSystem.getRootDirectory();//获取子文件UsbFile[] files = root.listFiles();//创建文件夹UsbFile newDir = root.createDirectory("record");//创建文件UsbFile newFile = newDir.createFile(Util.getSimpleFormatTime() + ".csv");// 写入文件OutputStream os = new UsbFileOutputStream(file);os.write("hello".getBytes());os.close();// 读取InputStream is = new UsbFileInputStream(file);byte[] buffer = new byte[currentFs.getChunkSize()];is.read(buffer);//使用其他方法OutputStream os = UsbFileStreamFactory.createBufferedOutputStream(file, currentFs);InputStream is = UsbFileStreamFactory.createBufferedInputStream(file, currentFs);//最后关闭device.close();
