androidkotlinusb-otgusb-mass-storage

How to remove LOST.DIR folder from USB Mass Storage in Android programmatically


I copy files from Android internal storage to USB drive, folder LOST.DIR always is created by system. How can I remove this folder programmatically

I use library libaums to handle communicate with USB I tried to delete this folder after copy but USB get error

    private fun exportOnlyFilesToUsb(fileSystem: FileSystem, file: File) {
        val root = fileSystem.rootDirectory
        if (!file.isDirectory) {
            root.search(file.name)?.delete()
            val targetFile = root.createFile(file.name)
            copyFile(file, targetFile)
            return
        }
        file.listFiles()?.forEach {
            exportOnlyFilesToUsb(fileSystem, it)
        }
    }

    private fun copyFile(file: File, usbFile: UsbFile) {
        if (file.isDirectory || usbFile.isDirectory) return
        FileInputStream(file).use { input ->
            UsbFileOutputStream(usbFile).use { output ->
                input.copyTo(output)
            }
        }
    }

// Then I delete 
root.search(LOST_DIR)?.delete()

Solution

  • First check if you have write access with File.canWrite().

    I think you have no write access to removable media since Android KitKat.

    You would need SAF and let the user select the directory with ACTION_OPEN_DOCUMENT_TREE.

    Yes it is a nuisance as the medium will be used in other devices which sometimes dont like that directory.

    The same counts for an Android directory that is often created.

    Yes remove all. Nobody asked for it.