I want to read/write OTG USB storage from device. For that I have written the code below but it shows only the SD card.
HashSet<String> out = new HashSet<String>();
String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
String s = "";
try {
final Process process = new ProcessBuilder().command("mount")
.redirectErrorStream(true).start();
process.waitFor();
final InputStream is = process.getInputStream();
final byte[] buffer = new byte[1024];
while (is.read(buffer) != -1) {
s = s + new String(buffer);
}
is.close();
} catch (final Exception e) {
e.printStackTrace();
}
// parse output
final String[] lines = s.split("\n");
for (String line : lines) {
if (!line.toLowerCase(Locale.US).contains("asec")) {
if (line.matches(reg)) {
String[] parts = line.split(" ");
for (String part : parts) {
if (part.startsWith("/"))
if (!part.toLowerCase(Locale.US).contains("vold"))
out.add(part);
}
}
}
}
for (String s3 : out ) {
Toast.makeText(getApplicationContext(),s3,Toast.LENGTH_LONG).show();
System.out.println("Value: " +s3);
}
With the code above I am able to get external SD card but not able to read USB with OTG.
How can I get USB storage also?
I've looked at your other questions regarding OTG access, and I think you're making it hard on yourself. The easiest way IMO to access/read/write OTG on a very wide range of devices is by querying all these directories, and using shell to read/write to them:
/storage/UsbDriveA (all Samsung devices)
/storage/USBstorage1 (LG G4, V10, G3, G2, other LG devices)
/storage/usbdisk (Moto Maxx, Turbo 2, Moto X Pure, other Motorola devices)
/storage/usbotg (Sony Xperia devices, Lenovo Tabs)
/storage/UDiskA (Oppo devices)
/storage/usb-storage (Acer Iconia Tabs)
/storage/usbcard (Dell Venue -- Vanilla Android 4.3 tablet)
/storage/usb (HTC One M7, and some Vanilla Android devices)
Tested on my collection of devices (and a few others'), and a quick trip to Bestbuy for testing the latest flagships. The only popular devices I know I'm missing are Hawuei/Xioami devices based in China, which are becoming popular in English countries.
You would be using Runtime.exec()
or ProcessBuilder
and testing the length of the ls
command output on each directory (to find the mounted USB directory), and cp
or redirection >
to write files to the pendrive, and cat
to read off the pendrive.
Hope this helps
来源:https://stackoverflow.com/questions/36060221/how-to-read-otg-usb-storage