How to get absolutePath of a usb device on linux/ubuntu with java

Multi tool use
How to get absolutePath of a usb device on linux/ubuntu with java
i am working on a method to import files which are stored on an usb device to my database.
I already done it for Mac and Windows, but I don't know how to get the path to the usb device when the application is used under Linux/Ubuntu with java.
Is there a way to find the path?
/media/...
Fedora systems, at least, don't auto-mount on
/media
any more. It's problematic to assume that all Linux systems treat removable media the same way. They don't, unfortunately.– Kevin Boone
Oct 10 '17 at 8:05
/media
2 Answers
2
I don't think there is any way that is guaranteed to work on all Linux systems. There are a few approaches I have used, with varying degrees of success.
A method that requires no external utilities is to enumerate and parse the pseudo-files in /dev/disk
, /proc/mounts
, and /sys/bus/usb
, and build a representation of the USB devices that hold storage. There might be more than one, so you might still have to make some guesses, or offer users a choice. This is a pretty tedious method, but I think it is the most general. You can just look at /media
, /run/media
, as somebody else suggested, but this only works on some Linux installations, and only if that form of auto-mounting is enabled.
/dev/disk
/proc/mounts
/sys/bus/usb
/media
/run/media
A less tedious approach is to invoke the utility udisksctl
from your program. I think this utility exists for almost all Linux variants, but it isn't always installed by default. The output of the utility has to be parsed, but it's less hassle that working directly with the kernel psedofiles.
udisksctl
To get a list of disk devices, execute udisksctl status
. This will tell you the model name, which will often include the text "USB", and the block device (e.g., /dev/sdb). Then you can execute udisksctl info -b /dev/sdb
and look for the line that begins "MountPoints". If the device is not mount you could, if you wished, force it by executing udisksctl mount...
. There's a heap of other useful stuff that udisksctl can do -- see its man page.
udisksctl status
udisksctl info -b /dev/sdb
udisksctl mount...
In Java you can use Runtime.exec()
to run udisksctl
, but it's probably friendlier to users to check that it is installed first, by check for the existence of /usr/bin/udisksctl
.
Runtime.exec()
udisksctl
/usr/bin/udisksctl
The easiest way I found is using the Volumes directory.
/Volumes/NAME_OF_USB_DRIVE/file.whatever
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
follow the path
/media/...
– T. Obadiah
Oct 10 '17 at 7:49