[关闭]
@Tyhj 2018-05-12T11:54:08.000000Z 字数 1584 阅读 2964

在Android中读写U盘

Android


https://www.zybuluo.com/Tyhj/note/1144629
最近工作中遇到数据从U盘导出的功能,网上找了一下,有个开源的框架可以拿来使用,U盘和内存卡什么的不一样,是用OTG口来连接手机的,有些手机不支持,有些手机支持,U盘格式也有几种,常见的exFAT、FAT32、NTFS,有些手机可能不支持所有格式的U盘,

开源库地址:https://github.com/magnusja/libaums

  1. //导入依赖:
  2. compile 'com.github.mjdev:libaums:0.5.5'
  1. //获取到OTG连接的U盘
  2. public static FileSystem otgGet(Context context) {
  3. UsbMassStorageDevice[] devices = UsbMassStorageDevice.getMassStorageDevices(context);
  4. FileSystem currentFs = null;
  5. for (UsbMassStorageDevice device : devices) {//一般只有一个OTG借口,所以这里只取第一个
  6. try {
  7. device.init();
  8. //如果设备不支持一些格式的U盘,这里会有异常
  9. if (device == null || device.getPartitions() == null ||
  10. device.getPartitions().get(0) == null ||
  11. device.getPartitions().get(0).getFileSystem() == null) {
  12. return null;
  13. }
  14. currentFs = device.getPartitions().get(0).getFileSystem();
  15. Log.e("OTG", "容量: " + currentFs.getCapacity());
  16. Log.e("OTG", "已使用空间: " + currentFs.getOccupiedSpace());
  17. Log.e("OTG", "剩余空间: " + currentFs.getFreeSpace());
  18. Log.e("OTG", "block数目: " + currentFs.getChunkSize());
  19. } catch (Exception e) {
  20. return null;
  21. }
  22. }
  23. return currentFs;
  24. }
  1. //获取根目录
  2. UsbFile root = fileSystem.getRootDirectory();
  3. //获取子文件
  4. UsbFile[] files = root.listFiles();
  5. //创建文件夹
  6. UsbFile newDir = root.createDirectory("record");
  7. //创建文件
  8. UsbFile newFile = newDir.createFile(Util.getSimpleFormatTime() + ".csv");
  9. // 写入文件
  10. OutputStream os = new UsbFileOutputStream(file);
  11. os.write("hello".getBytes());
  12. os.close();
  13. // 读取
  14. InputStream is = new UsbFileInputStream(file);
  15. byte[] buffer = new byte[currentFs.getChunkSize()];
  16. is.read(buffer);
  17. //使用其他方法
  18. OutputStream os = UsbFileStreamFactory.createBufferedOutputStream(file, currentFs);
  19. InputStream is = UsbFileStreamFactory.createBufferedInputStream(file, currentFs);
  20. //最后关闭
  21. device.close();
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注