android u盘加载_在Android中读写U盘

一时失言乱红尘 2022-10-24 05:52 349阅读 0赞

原文链接: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();

发表评论

表情:
评论列表 (有 0 条评论,349人围观)

还没有评论,来说两句吧...

相关阅读

    相关 U速度优化

    从android设备上向U盘上传文件,时间比较长,优化后,时间大幅度缩短 经过几次测试,8k的缓存可以达到传输速度和容错率的平衡点,超过了太容易出错,低于8k传输速度会下降。