美文网首页
Android 读取U盘路径和读写文件

Android 读取U盘路径和读写文件

作者: sssssss_ | 来源:发表于2023-05-22 17:40 被阅读0次

一、使用第三方库

libaums

二、参考文章

https://juejin.cn/post/7062361311367135263

三、解决问题

  1. 依赖问题需要剔除冲突
    api('me.jahnen.libaums:core:0.9.1', {
        exclude group: 'androidx.annotation', module: 'annotation'
        exclude group: 'androidx.core', module: 'core-ktx'
        exclude group: 'androidx.core', module: 'core'
    })

四、测试代码

 UsbMassStorageDevice[] devices = UsbMassStorageDevice.getMassStorageDevices(context);
            for (UsbMassStorageDevice device : devices) {

                // before interacting with a device you need to call init()!
                try {
                    device.init();
                    // Only uses the first partition on the device
                    FileSystem currentFs = device.getPartitions().get(0).getFileSystem();
                    Logg.d(TAG, "Capacity: " + currentFs.getCapacity());
                    Logg.d(TAG, "Occupied Space: " + currentFs.getOccupiedSpace());
                    Logg.d(TAG, "Free Space: " + currentFs.getFreeSpace());
                    Logg.d(TAG, "Chunk size: " + currentFs.getChunkSize());


                    UsbFile root = currentFs.getRootDirectory();

                    UsbFile[] files = root.listFiles();
                    for (UsbFile file : files) {
                        Logg.d(TAG, file.getName());
                        if (!file.isDirectory()) {
                            Logg.d(TAG, file.getLength() + "");
                        }
                    }

//                UsbFile newDir = root.createDirectory("foo");
//                UsbFile file = newDir.createFile("bar.txt");
//
//// write to a file
//                OutputStream os = new UsbFileOutputStream(file);
//
//                os.write("hello".getBytes());
//                os.close();
//
//// read from a file
//                InputStream is = new UsbFileInputStream(file);
//                byte[] buffer = new byte[currentFs.getChunkSize()];
//                is.read(buffer);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

五、效果

image.png

相关文章

网友评论

      本文标题:Android 读取U盘路径和读写文件

      本文链接:https://www.haomeiwen.com/subject/xxltedtx.html