Disclaimer

The views expressed on this blog are my own and do not necessarily reflect the views of Oracle.

Tuesday, May 27, 2008

Playing more with "ejectDrive"

Now start playing with the same program by using the power of netbeans :

At first , click on the 'Runtime' of the following line
'Runtime.getRuntime().exec("eject cdrom");'
Now , you will get a yellow bulb in the left of the editor , same line position. click on it and it will tell you to "Assign Return Value to Variable". click on this line and
'Runtime.getRuntime().exec("eject cdrom");'
will be converted to
'Process exec = Runtime.getRuntime().exec("eject cdrom");'

We will use this exec variable later to perform some another job.

When you executing the command "eject cdrom" in a terminal window , (I am using sxde 9/07) you will get something like :
bash-3.2$ eject cdrom
cdrom /dev/dsk/c0t0d0s2 ejected


Now if you want to print this line : 'cdrom /dev/dsk/c0t0d0s2 ejected' from your program you need to add the following lines in your code :

BufferedReader in = new BufferedReader(new InputStreamReader(exec.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.print(line + "\n");
}


Now use netbeans code completion tool to write programs more easily.
Just write "Bu" and press [CTRL]+[SPACE] and you will get a drop down list of all which starts with 'Bu'. Use arrow cursors to find out BufferReader and press [RETURN].

In the same line when you are writing .....new InputStreamReader(exec.getInputStream()) , wait after writing 'exec.'..... and choose 'getInputStream' from the drop down box.

Now check out that 'BufferReader' and 'InputStreamReader' is underlined by red color which means there's an error in the code . you will also find a red bulb beside. Place your mouse cursor on it to get probable cause of the error and click on it to get possible solution. Just click on it and choose 'Add Import for java.io.BufferReader' etc.

So now everything is complete , indent / format using [CTRL]+[ALT]+[F] and save [CTRL]+[S].

Now 'Main.java' should look like :

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ejectdrive;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
*
* @author ritwik
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try {
Process exec = Runtime.getRuntime().exec("eject cdrom");
BufferedReader in = new BufferedReader(new InputStreamReader(exec.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.print(line + "\n");
}
} catch (Exception e) {
System.out.print(e);
}
}
}


Run your program to get desirable output.

No comments:

Post a Comment