Pregunta

I have a Java application that is designed to run on removable drives. I would like to add a button to allow the user to safely remove the drive the program runs on as USB Disk Ejector allows. However, I'm not sure how to achieve this (code wise) as the drive cannot be ejected if the program is running from it. I know that this program is open source, but I don't know where to find the code I am looking for and it isn't written in a language I have learnt.

I would therefore very much appreciate it if somebody could help me work out how to achieve this functionality in my Java application. Obviously I don't want to just copy, but the only thing I know at the minute is I have to pass control over to some sort of temporary script that is not on the drive I wish to eject.

Thanks in advance

¿Fue útil?

Solución

As far as I know, it is not possible to implement this in pure Java as operations such as ejecting/unmounting drives are operating system-specific and not included in the default Java library which usually only supports the lowest common denominator. You need to execute some platform-specific code either by executing a script/batch file or by running native code written e.g. in C using Java's JNI mechanism.

Otros consejos

You're right that you will need to run the application from another drive. I would follow the Java Web Start CD Install guide, which should work just as well for a USB drive or any other media as it does for CDs.

You would need to make your application a Java Web Start application. It's actually much easier than it sounds; your .jar does not need to change, you just create a small XML file with a .jnlp extension and place it next to the .jar file. Information on Java Web Start and JNLP files can be found in the tutorial and in the links at the bottom of that page.

Your external executable which performs the safe removal can be included in your application .jar file. You can copy it from your .jar to a temporary file in order to run it:

Path safeRemovalProgram = Files.createTempFile(null, ".exe");
try (InputStream stream =
        MyApp.class.getResourceAsStream("saferemoval.exe")) {
    Files.copy(stream, safeRemovalProgram,
        StandardCopyOption.REPLACE_EXISTING);
}
safeRemovalProgram.toFile().setExecutable(true);

ProcessBuilder builder =
    new ProcessBuilder(safeRemovalProgram.toString());
builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
Process safeRemovalProcess = builder.start();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top