This is how to eject a CD Tray in Java without using JNI.
From Michael Dunn :
class OpenCD
{
public OpenCD()
{
try
{
String driveLetter = javax.swing.JOptionPane.showInputDialog("Enter CD drive letter");
if(driveLetter != null)
{
java.io.File file = new java.io.File("OpenCD.vbs");
java.io.FileWriter fw = new java.io.FileWriter(file);
fw.write("CreateObject(\"Shell.Application\").NameSpace(17).ParseName(\""+driveLetter+"\" & \":\\\").InvokeVerb(\"e&ject\")");
fw.close();
Runtime.getRuntime().exec("WScript.exe openCD.vbs");
Thread.sleep(2000);
file.deleteOnExit();
}
}
catch(Exception e){e.printStackTrace();}
System.exit(0);
}
}
Call it as new OpenCD() from within static main.
It works.
This is better, it can eject and also close, from rgagnon:
class CDUtils {
private CDUtils() { }
public static void open(String drive) {
try {
File file = File.createTempFile("realhowto",".vbs");
file.deleteOnExit();
FileWriter fw = new java.io.FileWriter(file);
String vbs = "Set wmp = CreateObject(\"WMPlayer.OCX\") \n"
+ "Set cd = wmp.cdromCollection.getByDriveSpecifier(\""
+ drive + "\") \n"
+ "cd.Eject";
fw.write(vbs);
fw.close();
Runtime.getRuntime().exec("wscript " + file.getPath()).waitFor();
// thanks to TrueJavaProgammer for the waitFor() tip!
// Runtime.getRuntime().exec("wscript " + file.getPath()).waitFor();
// Thread.sleep(2000);
}
catch(Exception e){
e.printStackTrace();
}
}
public static void close(String drive) {
try {
File file = File.createTempFile("realhowto",".vbs");
file.deleteOnExit();
FileWriter fw = new FileWriter(file);
// to close a CD, we need eject two times!
String vbs = "Set wmp = CreateObject(\"WMPlayer.OCX\") \n"
+ "Set cd = wmp.cdromCollection.getByDriveSpecifier(\""
+ drive + "\") \n"
+ "cd.Eject \n "
+ "cd.Eject ";
fw.write(vbs);
fw.close();
Runtime.getRuntime().exec("wscript " + file.getPath()).waitFor();
// thanks to TrueJavaProgammer for the waitFor() tip!
// Runtime.getRuntime().exec("wscript "+ file.getPath());
// Thread.sleep(2000);
}
catch(Exception e){
e.printStackTrace();
}
}
}
Call the static open and close methods from main:
CDUtils.open("E:\\");
or
CDUtils.close("E:\\");