在Android中读写U盘

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

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

//导入依赖:
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();
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 作者:傅尊翔 链接:https://www.zhihu.com/question/21698655/answer/...
    你说你要一场阅读 1,011评论 0 0
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,778评论 25 709
  • U盘安装win 10 1、U盘格式化类型:exFAT>NTFS>FAT32 2、MBR与GPT理解: 3、Win1...
    comyn_sheng阅读 3,245评论 0 0
  • 最近在Android上测试64GB的TF卡支持情况,发现在Windows平台上默认会把卡格式化为exFAT,而不是...
    网路元素阅读 2,563评论 0 1
  • 每一刻都是礼物 即使你称之为坏的也是礼物 跌倒也是礼物 这些是为了变的更好 如果你能看见生活有多美 你的生活就会更...
    林锋Frank阅读 222评论 0 1