Wednesday, May 27, 2009

What does rt.jar stand for in Java/JDK/JRE?

The most likely answer is, rt stands for RunTime. Some tend to think it stands for RooT, since this jar contains all java build-in classes. But I have yet to find any official Sun documents regarding this acronym.
Whether it stands for RunTime, RooT, or anything else is not important. The question I have is, why would the java creator chose to use such a undescriptive name. Maybe it can make your classpath shorter? But we rarely put rt.jar in system classpath.
Here are 2 reasons I don't like the name rt.jar:
* While experienced developers take it for granted, java beginners don't know what it is other than it's a jar. So it's one more questions in beginners' mind.
* The shorter the name, the easier it is to cause naming conflicts, at least visually. While rt.jar will always reside under $JAVA_HOME/jre/lib, it is possible your applications may have another jar also named rt.jar.
I know rt.jar will be with us as long as java is, but just for the sake of discussion, how would you name it differently? Maybe java.jar, or java-core.jar?
PS: What does jar stand for? Jar stands for Java Archive. A jar file usually has file name extension .jar. It contains mainly java class files but any types of files can be included, e.g., XML files, HTML files, properties files, gif/jpg image files, text files, PDF files, and binary files, and so on.
PS: What is the difference between a jar file and a zip file? Basically, a jar file is the same as a zip file, except that the jar file contains a META-INF directory to store metadata or attributes. The most well-known file is META-INF/MANIFEST.MF. You can customize the content of a MANIFEST.MF when creating a jar file, and if you don't, a default one is generated and included. For example:
Manifest-Version: 1.0
Created-By: 1.5.0_06 (Sun Microsystems Inc.)
It's perfectly fine to have other configuration files and directories under META-INF.

Java Jar File Naming Conventions and Examples.

util.jar is the worst jar file name I can think of. All I know is it contains some utility/helper classes. But it is unclear if they belong to an application server, or a framework, or any application sub-systems. You will need to ask someone or some docs to know what it is. It's part of the DataDirect JDBC Driver distribution.
On the other hand, good jar file names are always self-explanatory, for example: struts.jar, jboss-system.jar, commons-pool-1.1.jar
Some thoughts on jar file naming conventions:
1. Always use extension ".jar", not ".zip"
Theoretically, jar files can have any extension or no extension at all. If you specify it in the system classpath, it should be loadable. The problem is with automatic library detection and loading by containers and frameworks. It's expensive to scan all files so some sort of extension restriction is needed. For this reason, J2EE/JavaEE platform spec requires all library jar files use ".jar" extension, such as WEB-INF/lib/mybeans.jar.
2. Use hyphen (-) instead of underscore (_) as word separator
First, it's easier to type - than _; secondly, when the file name is underlined (e.g., in a hyperlink), the _ is invisible. Hyphen has been shunned in file names partly because it is an illegal character in java identifier. But this concern is unwarranted.
3. Append version number if distributed standalone
because they can be dropped into any applications, which may need specific versions. We don't want users to have to compare file size or extract some META-INF files to know its version. Some examples: hibernate3.jar, commons-logging-1.0.3.jar, and
log4j-1.2.8.jar.
4. Don't append version number if bundled inside other larger deliverables
because the enclosing deliverables, such as an application server (e.g., JBoss 4.0.4, jakarta-tomcat-5), a tool(e.g., apache-ant-1.6.5), aleady have the version numbers, thus no version number for jboss.jar, catalina.jar, and ant.jar.

The Worst Java Job Interview Questions.

Why are you looking for a job?
Strictly speaking, this is not a java question, but it shows up in almost every job interview I've been to. The interviewer is testing the candidate's motivation for a job change. Invariably, the answer will be something like, advancing career and professional development. Of course, the candidate won't tell you he/she is looking for a 15% salary increase to cover the gas price increase, or he doesn't get along with his co-workers, or he didn't get the promotion or bonus, or he was rated Under-Perform in last year's performance review.
Which OS do you use in your development work, Linux, Windows, or Solaris?
Java is cross-platform, and I couldn't care less about OS while I'm writing java code. Unless the job is specifically about porting applications to other OS and deploying/distributing applications, I don't see how this is relevant. J2EE, JavaEE and Web applications are all made up of components that are managed by the application server, and thus shielded from the underlying OS.
Are you familiar with Oracle Database, or DB2?
Java persistence can now be easily achieved with ORM frameworks such as Hibernate, TopLink. The latest release of EJB 3 and Java Persistence API has standardize the way persistence is done in Java, J2EE, and JavaEE. The goal of these industry efforts is to let Java developers forget database stuff, which should be left to DBA. Even if Java developers in this project need to deal with database directly, I suppose they need to know about database design concepts and SQL, not some Oracle or DB2 stored procedures.

A New Option in Jar Command in JDK 6

DK 6 adds a new feature to the jar command: e. Other options of the jar command are still the same. This is the partial usage from JDK 6 beta 2:
C:\tools\jdk6\bin>jar
Usage: jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] files ...
Options:
...
-e specify application entry point for stand-alone application
bundled into an executable jar file
...
For example, I run jar command to package a self-contained application in a jar file:
C:\ws\nb\scrap\build\classes>C:\tools\jdk6\bin\jar cvfe ..\..\dist\hello-world.jar com.javahowto.test.HelloWorld com
added manifest
adding: com/(in = 0) (out= 0)(stored 0%)
adding: com/javahowto/(in = 0) (out= 0)(stored 0%)
adding: com/javahowto/test/(in = 0) (out= 0)(stored 0%)
adding: com/javahowto/test/HelloWorld.class(in = 572) (out= 348)(deflated 39%)
Then I can distribute hello-world.jar to users, who can run hello-world app like this:
C:\download\hello>java -jar hello-world.jar
Hello world!
Users can run it with any version of java; it doesn't have to be JDK 6. What the extra e option does is simply adding a Main-Class entry in the jar's META-INF\MANIFEST.MF:
Manifest-Version: 1.0
Created-By: 1.6.0-beta2 (Sun Microsystems Inc.)
Main-Class: com.javahowto.test.HelloWorld
This new feature is helpful when packaging simple self-contained apps, and application client modules in J2EE/JavaEE, both of them require a Main-Class entry in MANIFEST.MF. So I don't have to create one beforehand, or have Apache Ant generate one.

How to run Tomcat manager web application

1. Add the security role manager to $CATALINA_HOME/conf/tomcat-users.xml, and assign this role to a username, say tomcat:


2. Start Tomcat:
$CATALINA_HOME/bin/startup.sh
(%CATALINA_HOME%\bin\startup.bat on windows)
3. Browser the URL http://localhost:8080, and click the Tomcat Manager link on the upper-left corner. In the basic login page, enter username tomcat and password tomcat, as specified in conf/tomcat-users.xml. Tomcat Manager web application allows you to view Tomcat server info, deploy and undeploy webapps, and other simple management tasks.

Who set my CLASSPATH?

I never set CLASSPATH environment variable. Instead I always use the explicit -classpath or -cp options when running java, javac, javap, etc. The other day I was surprised to see a CLASSPATH environment variable is set:
C:\tmp> set CLASSPATH
CLASSPATH=.;C:\Program Files\Java\jre1.5.0_09\lib\ext\QTJava.zip
C:\tmp> dir "C:\Program Files\Java\jre1.5.0_09\lib\ext\QTJava.zip"
06/12/2006 09:57 AM 1,180,476 QTJava.zip
It seems when I installed apple's quicktime plugin, it automatically set this CLASSPATH in my environment. I don't like this. I always assume a clean environment when running any java applications. So I removed it:
C:\tmp> set CLASSPATH=
C:\tmp> set CLASSPATH
Environment variable CLASSPATH not defined
I can tolerate an installer modifying my PATH, but not CLASSPATH.

Line tools NetBeans plugin

I don't like overloading my IDE with a bunch of plugins, but this is a must-have for my NetBeans (currently version 5.5.1).
[Update] Those features in line tool has been integrated into NetBeans proper 6.x. So if you are running NetBeans 6.1 (the latest as of 5/2008), line tool plugin is no longer needed.
I use it everyday to copy and paste lines of text without using CTRL-C CTRL-V. This is its official description:
Line Tools Support following operations in text editors:
1. Move Line (or lines spanned by selection) Up
2. Move Line (or lines spanned by selection) Down
3. Copy Line (or lines spanned by selection) Up
4. Copy Line (or lines spanned by selection) Down
5. Sort lines spanned by selection in ascending order
6. Sort lines spanned by selection in descending order
7. Remove duplicate lines while sorting. Maintain the caret position, the selection and the order of start and end of the selection when moving/copying the lines.
This is the first plugin I will install for every new NetBeans release. Unfortunately, NetBeans can't automatically migrate my installed plugins.
Oddly, this plugin doesn't show up in the official NetBeans plugin portal. The place to go is the author's (Sandip Chitale) blog.
You can choose either download the *.nbm file and manually install it, or add a new update center (Sandip Chitale's update center) to your NetBeans. After adding the update center, you will able to download a lot more good stuffs by Sandip Chitale.

How to create a thread

Execution in Java always take form of a thread. In simple programs only one thread occurs, often referred to as the 'main thread'.
In some programs though concurrent threads is necessary, or if you are building a Swing application with for example a progress bar you don't want the main thread to handle the updates of the UI.
Then you create an additional thread to take care of that. There are two main ways of creating a thread. The first is to extend the Thread class and the second is to implement the Runnable interface.
Extending Thread:
 
public class MyThread extends Thread {
/**
* This method is executed when the start() method is called on the thread
* so here you will put the 'thread code'.
*/
public void run() {
System.out.println("Thread executed!");
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Thread thread = new MyThread();
thread.start();
}
}
Implementing the Runnable interface:
 
public class MyRunnable implements Runnable {
/**
* As in the previous example this method is executed
* when the start() method is called on the thread
* so here you will put the 'thread code'.
*/
public void run() {
System.out.println("Thread executed!");
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//create a Thread object and pass it an object of type Runnable
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}

Setting thread priorities

Setting a threads priority can be very useful if one thread has more critical tasks to perform than another.
The Thread class has a method called setPriority(int level) with which you can alter the priority a Thread instance has.
The priority level range from 1 (least important) to 10 (most important) and if no level is explicitly set, a Thread instance has the priority level of 5.
In the first example below no priorites are set, so both threads have the priority level 5. The TestThread class implements the Runnable interface and in its
run() method loops from 1 to 10 and output the number along with its Thread id, which is passed to the constructor.
 
/**
* Main.java
*
* @author
*/
public class Main {
/**
* Starts two threads and wait for them to finish.
*/
public void setPrioritiesOnThreads() {
Thread thread1 = new Thread(new TestThread(1));
Thread thread2 = new Thread(new TestThread(2));
thread1.start();
thread2.start();
try {
//Wait for the threads to finish
thread1.join();
thread2.join();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
System.out.println("Done.");
}
/**
* Starts the program
*
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().setPrioritiesOnThreads();
}
class TestThread implements Runnable {
int id;
public TestThread(int id) {
this.id = id;
}
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("Thread" + id + ": " + i);
}
}
}
}
 
 
 
Since both threads have the same priority, the output will be a mix between them and could look like this:
 
Thread2: 1
Thread1: 1
Thread2: 2
Thread1: 2
Thread2: 3
Thread1: 3
Thread2: 4
Thread1: 4
Thread2: 5
Thread1: 5
Thread2: 6
Thread1: 6
Thread2: 7
Thread2: 8
Thread2: 9
Thread2: 10
Thread1: 7
Thread1: 8
Thread1: 9
Thread1: 10
Done.
 
The output could look different from on execution to another since we have no control of how the CPU will prioritize them.
If we set the priority on the threads we still haven't got exact control of the execution, but at least we can tell the CPU which one we think is
most important. The next example is identical to the one above except for the lines where the priority of the threads are set:
 
/**
* Main.java
*
* @author
*/
public class Main {
/**
* Starts two threads, setting priorities on them
* and wait for them to finish.
*
*/
public void setPrioritiesOnThreads() {
Thread thread1 = new Thread(new TestThread(1));
Thread thread2 = new Thread(new TestThread(2));
//Setting priorities on the Thread objects
thread1.setPriority(Thread.MAX_PRIORITY);
thread2.setPriority(Thread.MIN_PRIORITY);
thread1.start();
thread2.start();
try {
//Wait for the threads to finish
thread1.join();
thread2.join();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
System.out.println("Done.");
}
/**
* Starts the program
*
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().setPrioritiesOnThreads();
}
class TestThread implements Runnable {
int id;
public TestThread(int id) {
this.id = id;
}
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("Thread" + id + ": " + i);
}
}
}
}
 
 
The output from the code looked like this when executed:
 
Thread1: 1
Thread1: 2
Thread1: 3
Thread1: 4
Thread1: 5
Thread1: 6
Thread1: 7
Thread1: 8
Thread1: 9
Thread1: 10
Thread2: 1
Thread2: 2
Thread2: 3
Thread2: 4
Thread2: 5
Thread2: 6
Thread2: 7
Thread2: 8
Thread2: 9
Thread2: 10
Done.
 
It is however not certain that the first thread will be prioritized to finish before the second thread starts every time.
It is, as mentioned earlier, up to the CPU to decide.

Remove duplicate items from an ArrayList

This code example shows how to remove duplicate items from an ArrayList.

ArrayList arrayList1 = new ArrayList();
arrayList1.add("A");
arrayList1.add("A");
arrayList1.add("B");
arrayList1.add("B");
arrayList1.add("B");
arrayList1.add("C");
//Create a HashSet which allows no duplicates
HashSet hashSet = new HashSet(arrayList1);
//Assign the HashSet to a new ArrayList
ArrayList arrayList2 = new ArrayList(hashSet) ;
//Ensure correct order, since HashSet doesn't
Collections.sort(arrayList2);
for (Object item : arrayList2)
System.out.println(item);



Note that you will have to sort the ArrayList if you want to be sure that the items remain
in correct order by calling the sort method of the Collection class.
This will produce the following output:
A
B
C




Creating and storing arrays in a map

Sometimes you want to create variable names dynamically, for example in a loop. One way of doing this is to not create the variables with different names but rather to store them in a Collection object that takes a key-value pair.
You can provide a unique key for the variable and then store its reference as the value.
In this examples first method we create 9 arrays which we store in a Map, each with different names. In the example below we use a TreeMap.
In the second method we print out the names of each key, and loop through the values of its value object (which is an array).
 
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
/**
*
* @author
*/
public class Main {
Map map = new TreeMap();
/**
* Example method for creating and storing arrays in a map
*/
public void createArrays() {
for (int i = 1; i <= 9; i++) {
int[] array = new int[3];
array[0] = i;
array[1] = i + 1;
array[2] = i + 2;
map.put(("array_" + i), array);
}
}
/**
* Example method for printing arrays stored in a map
*/
public void printArrays() {
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
String arrayName = iter.next();
int[] array = map.get(arrayName);
System.out.println("Values for array " + arrayName + ":");
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
System.out.println();
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Main main = new Main();
main.createArrays();
main.printArrays();
}
}
The output of the code above will be:
Values for array array_1:
1
2
3
Values for array array_2:
2
3
4
Values for array array_3:
3
4
5
Values for array array_4:
4
5
6
Values for array array_5:
5
6
7
Values for array array_6:
6
7
8
Values for array array_7:
7
8
9
Values for array array_8:
8
9
10
Values for array array_9:
9
10
11

Convert a List (ArrayList) to an Array

This piece of Java code shows how to convert a List, in this case an ArrayList, to an Array by calling the method toArray() on the List object.
The toArray() method returns an array of the same type as the array provided as an argument to the method. The argument can be an empty array as in the example below.
 
/**
*
* @author
*/
public class Main {
public void ListToArray() {
List carList = new ArrayList();
carList.add("Dodge");
carList.add("Chevrolet");
carList.add("BMW");
carList.add("Toyota");
String[] carArray = carList.toArray(new String[0]);
for (String car : carArray) {
System.out.println(car);
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().ListToArray();
}
}
The code above generate the following output (the elements are ordered similarly in the array as in the list):
 
Dodge
Chevrolet
BMW
Toyota

Convert a List to a Set (ArrayList to HashSet)

This example shows how to convert from an ArrayList to a HashSet. Since most Collection objects have a constructor that allows for passing in another Collection object we are able to make these kinds of conversions easily.
In the example we create an ArrayList to which we add a few string items. Next we create a HashSet and provide the reference to the ArrayList as argument to the HashSet constructor.
Finally we just loop through the HashSet and print out the contents.
 
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
*
* @author
*/
public class Main {
/**
* Conversion from a List to a Set,
* or from an ArrayList to a HashSet object
*/
public void convertFromListToSet() {
List fruitsList = new ArrayList ();
fruitsList.add("Apples");
fruitsList.add("Bananas");
fruitsList.add("Oranges");
fruitsList.add("Grapes");
Set fruitsSet = new HashSet(fruitsList);
for (Object theFruit : fruitsSet)
System.out.println(theFruit);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertFromListToSet();
}
}
The output from the code is not surprisingly the items in the same order as added to the ArrayList:
Apples
Bananas
Oranges
Grapes

Convert LinkedList to Array

This code example shows how to convert a LinkedList containing Strings to an array of Strings.
We begin by creating and populating the LinkedList with String representing different fruits. The actual conversion is done by calling the toArray() method of the list which returns the array. As input we create an empty String-array to tell the method to which type the elements should be converted.
There is actually another way of doing the conversion. Instead of passing an empty array to the toArray() method, we can pass an array of the same size as the List, and then it'll be populated with the elements. See an example further below.
 
package com.javadb.examples;
import java.util.LinkedList;
import java.util.List;
 
/**
*
* @author
*/
public class Main {
public void convertLinkedListToArray() {
List theList = new LinkedList();
theList.add("Apples");
theList.add("Bananas");
theList.add("Oranges");
theList.add("Grapes");
String[] fruits = theList.toArray(new String[0]);
for (int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
}
}
public static void main(String[] args) {
new Main().convertLinkedListToArray();
}
 
We could also have done the conversion like this:
 
String[] fruits = new String[theList.size()];
theList.toArray(fruits);
 
The output looks like this:
 
Apples
Bananas
Oranges
Grapes

List drives

This piece of code might come in handy on a Windows platform to list the drives of a computer.
 
import java.io.File;
public class FileUtil {
public void listDrives() {
File[] drives = File.listRoots();
for (int i = 0; i < drives.length; i++) {
System.out.println(drives[i]);
}
}
public static void main(String[] args) {
FileUtil fileutil = new FileUtil();
fileutil.listDrives();
}
}

Masking a password with the Console class

In Java 6 you can use the Console class to mask a password, or more precisely, no characters will be written as output to the console at all when you type the password.
This is achieved with help of the readPassword() method of the Console class. The method returns an array of char, which then easily is passed to the String class constructor to make it useful.
This example is best run in the console and not from within an IDE, since the System.console() method might return null in that case.
 
import java.io.Console;
/**
*
* @author
*/
public class Main {
/**
* Example method for entering password from the console
*/
public void passwordExample() {
Console console = System.console();
if (console == null) {
System.out.println("Couldn't get Console instance, maybe you're running this from within an IDE?");
System.exit(0);
}
console.printf("Testing password%n");
char passwordArray[] = console.readPassword("Enter your secret password: ");
console.printf("Password entered was: %s%n", new String(passwordArray));
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().passwordExample();
}
}

Using the RandomAccessFile class

This java code example illustrates how you can use the RandomAccessFile class.
The example in itself might seem pretty useless but the purpose is to show that you can both write to and read from a file with the same RandomAccessFile instance.
The RandomAccessFile class also enables you to get the current position of the file pointer by calling the method 'getFilePointer', or setting the file pointer position by calling the 'seek' method.
The behaviour of the RandomAccessFile class is similar to an array in the filesystem, but unlike an array you can alter the length of the file by calling the 'setLength' method.
If you are calling seek and then start to write data in an area that already contains data, it will be overwritten.
In this example we write two lines of code to the file, then we set the file pointer to the position at the end of the first line and read data from there and print it out.
 
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
*
* @author
*/
public class Main {
/**
* Example method for using the RandomAccessFile class
*/
public void testRandomAccessFile(String filename) {
RandomAccessFile randomAccessFile = null;
try {
//Declare variables that we're going to write
String line1 = "First line\n";
String line2 = "Second line\n";
//Create RandomAccessFile instance with read / write permissions
randomAccessFile = new RandomAccessFile(filename, "rw");
//Write two lines to the file
randomAccessFile.writeBytes(line1);
randomAccessFile.writeBytes(line2);
//Place the file pointer at the end of the first line
randomAccessFile.seek(line1.length());
//Declare a buffer with the same length as the second line
byte[] buffer = new byte[line2.length()];
//Read data from the file
randomAccessFile.read(buffer);
//Print out the buffer contents
System.out.println(new String(buffer));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (randomAccessFile != null)
randomAccessFile.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().testRandomAccessFile("myFile.txt");
}
}
The output to the file is:
First line
Second line
 
and the output to the console:
Second line

Reading objects from file using ObjectInputStream

This example shows how to read objects that has been serialized to a file with an ObjectOutputStream.
We simply create an instance of ObjectOuputStream and loop for as long as there are objects in the file.
The while condition could be argued since the readObject method will never return null, instead it will throw an EOFException when the end of the file is reached.
One could as well write 'while (true)' but as that is not good practice we won't do it here either. This example presumes that the number of objects in the file is unknown and therefore we cannot use a fixed number of iterations in the loop.
What this code example does instead is to catch the EOFException and just print out that the end of file is reached.
The file contains instances of the class Person and it was used in the corresponding example when an ObjectOutputStream was used to write objects to a file.
 
 
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
/**
*
* @author chintan patel
*/
public class Main {
/**
* Example method for using the ObjectInputStream class
*/
public void readPersons(String filename) {
ObjectInputStream inputStream = null;
try {
//Construct the ObjectInputStream object
inputStream = new ObjectInputStream(new FileInputStream(filename));
Object obj = null;
while ((obj = inputStream.readObject()) != null) {
if (obj instanceof Person) {
System.out.println(((Person)obj).toString());
}
}
} catch (EOFException ex) { //This exception will be caught when EOF is reached
System.out.println("End of file reached.");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the ObjectInputStream
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().readPersons("myFile.txt");
}
}
The output from the code above looks like this:
James
Ryan
19
Obi-wan
Kenobi
30
End of file reached.
 
 

Writing objects to file with ObjectOutputStream

You can use the ObjectOutputStream class to write objects to an underlying stream.
In this code example we use it to write objects to a file using the FileOutputStream class as argument to the ObjectOutputStream constructor.
The class from which we create objects to write is a simple java class with three attributes, first name, last name and age. The important thing here is that it implements the Serializable interface.
Any object that is written on an ObjectOutputStream is serialized and therefore has to implement either the java.io.Serializable interface or the java.io.Externalizable interface.
This is what the Person class looks like:
 
import java.io.Serializable;
/**
*
* @author chintan patel
*/
public class Person implements Serializable {
private String firstName;
private String lastName;
private int age;
/**
* Creates a new instance of Person
*/
public Person() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//Overriding toString to be able to print out the object in a readable way
//when it is later read from the file.
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(firstName);
buffer.append("\n");
buffer.append(lastName);
buffer.append("\n");
buffer.append(age);
buffer.append("\n");
return buffer.toString();
}
}
 
----------------------------------------------------------------------------------
 
 
 
This is the code for creating instances of the Person class and writing them to an ObjectOuputStream:
 
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
/**
*
* @author chintan patel
*/
public class Main {
/**
* Example method for using the ObjectOutputStream class
*/
public void writePersons(String filename) {
ObjectOutputStream outputStream = null;
try {
//Construct the LineNumberReader object
outputStream = new ObjectOutputStream(new FileOutputStream(filename));
Person person = new Person();
person.setFirstName("James");
person.setLastName("Ryan");
person.setAge(19);
outputStream.writeObject(person);
person = new Person();
person.setFirstName("Obi-wan");
person.setLastName("Kenobi");
person.setAge(30);
outputStream.writeObject(person);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the ObjectOutputStream
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().writePersons("myFile.txt");
}
}

List file structure within folder or hard drive

This code example lists the files and folders and also the content in all subfolders.
With recursive calls the file/directory tree can be listed with
a relatively small amount of code.
The purpose of the getTabs method and the variable tabCounter is only to
make the output more viewable with indenting for each level.
 
 
import java.io.File;
public class FileStructure {
int tabCounter = 0;
public void listFilesAndFolders(String folder) {
File file = new File(folder);
if (!file.exists() !file.isDirectory()) {
System.out.println("Parameter is not a directory");
System.exit(1);
}
File[] fileArray = file.listFiles();
for (int i = 0; i < fileArray.length; i++) {
if (fileArray[i].isDirectory()) {
System.out.println(getTabs() + "- " + fileArray[i].getName());
tabCounter++;
listFilesAndFolders(fileArray[i].getAbsolutePath());
}
else {
System.out.println(getTabs() + fileArray[i].getName());
}
}
tabCounter--;
}
private String getTabs() {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < tabCounter; i++)
buffer.append("\t");
return buffer.toString();
}
public static void main(String[] args) {
FileStructure fileStructure = new FileStructure();
fileStructure.listFilesAndFolders("C:\\temp");
}
}

Create a temporary file

Sometimes it come in handy to create a temporary file.
Here we create a temporary file with the prefix "temp_" as shown by the first parameter.
The second parameter is an optional suffix, if it\'s null as in the example, .tmp will be
used by default.
Optionally a third parameter can be defined pointing out the directory in which the file will
be created. If not specified (as below), the default temporary directory will be used.
 
 
import java.io.File;
import java.io.IOException;
public class FileUtil {
public void createTemporaryFile(String filename) {
try {
//Create the temp file
File f = File.createTempFile("temp_", null);
//Check where the default temp dir is located
System.out.println(f.getAbsolutePath());
//Delete the file when the program exists
f.deleteOnExit();
//Place any processing of the file here
// ...
}
catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
FileUtil fileutil = new FileUtil();
fileutil.createTemporaryFile("myfile.txt");
}
}

Read each line in a comma separated file into an array

In this example we read the lines of a comma separated file and split the values into an array.
This is done fairly easy with the split() method, which takes a separator as an argument and returns
an array of Strings.
 
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
 
public class CsvTest {
public void readFile() {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("thefile.csv"));
String line = null;
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
//Do necessary work with the values, here we just print them out
for (String str : values) {
System.out.println(str);
}
System.out.println();
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
finally {
try {
if (br != null)
br.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
CsvTest test = new CsvTest();
test.readFile();
}
}

List files of a certain type

To list files of a certain type, create an instance of the FileFilter
class and override it\'s accept method. Use that instance when calling
the list method of the File class.
 
import java.io.File;
import java.io.FilenameFilter;
public class FileUtil {
public void listFiles(String dir) {
File directory = new File(dir);
if (!directory.isDirectory()) {
System.out.println("No directory provided");
return;
}
//create a FilenameFilter and override its accept-method
FilenameFilter filefilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
//if the file extension is .txt return true, else false
return name.endsWith(".txt");
}
};
String[] filenames = directory.list(filefilter);
for (String name : filenames) {
System.out.println(name);
}
}
public static void main(String[] args) {
FileUtil fileutil = new FileUtil();
fileutil.listFiles("C:\\\\temp");
}
}

Remove a line from a text file

This example shows how to delete a line from a file.
The method removeLineFromFile takes two parameters, the first parameter is the file to remove from and the second parameter is the content of the line to remove.
A tempfile is created and written to, except for the content that matches the second parameter.
This way very large files can be handled without demanding so much internal memory.
The original file is then deleted and the tempfile is renamed to the original filename.
 
For example, the file test.txt is located in the current directory and contains three lines, and we will remove the second line "bbbbb".
 
 
aaaaa
bbbbb
ccccc
 
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
public class FileUtil {
 
public void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File(file);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
FileUtil util = new FileUtil();
util.removeLineFromFile("test.txt", "bbbbb");
}
}
The file test.txt now looks like this:
 
aaaaa
ccccc

How to create a zip file

This code example shows how to create a zip file.
What we do is to create an input stream from the file we want to compress, and while we read from it we write the contents to an output stream.
This output stream is of type ZipOutputStream which takes an FileOutputStream as parameter.
Next we have to add a zip entry to the output stream before we start writing to it.
We will also clean up by closing the zip entry and both the input stream and output stream when we are done.
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
*
* @author chintan patel
*/
public class Main {
/**
* Creates a zip file
*/
public void createZipFile() {
try {
String inputFileName = "test.txt";
String zipFileName = "compressed.zip";
//Create input and output streams
FileInputStream inStream = new FileInputStream(inputFileName);
ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipFileName));
// Add a zip entry to the output stream
outStream.putNextEntry(new ZipEntry(inputFileName));
byte[] buffer = new byte[1024];
int bytesRead;
//Each chunk of data read from the input stream
//is written to the output stream
while ((bytesRead = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, bytesRead);
}
//Close zip entry and file streams
outStream.closeEntry();
outStream.close();
inStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().createZipFile();
}
}

How to list the contents of a zip file

To list the contents of a zip file you need to get the entries of the file since every file in a zip file is represented by an entry.
In this case we assume that the filename of the zip file is 'testfile.zip'. By calling the entries method of the ZipFile object we get an Enumeration back that can be used to loop through the entries of the file.
Note that we have to cast each element in the Enumeration to a ZipEntry.
Normally some more extensive processing of the entries would probably be done, but here we just print out the name of each entry (i.e the name of the file or directory in the zip file).
 
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
*
* @author chintan patel
*/
public class Main {
public void listContentsOfZipFile() {
try {
ZipFile zipFile = new ZipFile("testfile.zip");
Enumeration zipEntries = zipFile.entries();
while (zipEntries.hasMoreElements()) {
//Process the name, here we just print it out
System.out.println(((ZipEntry)zipEntries.nextElement()).getName());
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().listContentsOfZipFile();
}
}

Extract contents of a zip file

This example shows how to extract a zipfile containing one file (or entry).
The name of the zip file is 'compressed.zip' and we want to write the contents to a file called 'extracted.txt'.
We start by opening an input stream to the compressed file and an output stream to the file where we want the content to be extracted.
After that we get the next entry of the zip file (and the only entry in this case) - test so it's not null, and then start reading the contents from the input stream and writing each chunk read to the output stream.
As usual we should clean up properly afterwards so we close the input and output streams.
 
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
*
* @author chintan patel
*/
public class Main {
/**
* Extracts a zip file
*/
public void extractZipFile() {
try {
String zipFileName = "compressed.zip";
String extractedFileName = "extracted.txt";
//Create input and output streams
ZipInputStream inStream = new ZipInputStream(new FileInputStream(zipFileName));
OutputStream outStream = new FileOutputStream(extractedFileName);
ZipEntry entry;
byte[] buffer = new byte[1024];
int nrBytesRead;
//Get next zip entry and start reading data
if ((entry = inStream.getNextEntry()) != null) {
while ((nrBytesRead = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, nrBytesRead);
}
}
//Finish off by closing the streams
outStream.close();
inStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().extractZipFile();
}
}

Convert a String to int

Use the static method parseInt of the Integer class to convert
a String to an int as below:
 
public void convertStringToInt() {
String sValue = "5";
int iValue = 0;
try {
iValue = Integer.parseInt(sValue);
}
catch (NumberFormatException ex) {
System.out.println("The String does not contain a parsable integer");
}
//Additional code goes here...
}
 
 
 
 
 
Alternatively you can pass a String to the Integer class constructor
and call the intValue-method of the object:
 
 
public void convertStringToInt() {
String sValue = "5";
int iValue;
try {
iValue = new Integer(sValue).intValue();
}
catch (NumberFormatException ex) {
System.out.println("The String does not contain a parsable integer");
}
//Additional code goes here...
}

Convert an int value to String

This code example shows how to convert an int value to a String object.
Actually there are a few possible ways of doing this and three of the most common methods of doing so is presented here.
First we use the static method toString() of the Integer class which takes an integer as argument and returns a String.
The second way of converting from int to String is to instantiate the Integer class and pass the int value to the constructor, and then call the toString() method on the object.
Finally the easiest way of converting from datatype int to String is to simply concatenate the int value to an empty String. That way the value will automatically be converted and appended to the String.
After every conversion the converted value along with the method of which it was converted is printed out to show that the object returned is really an instance of the String class.
 
 
 
/*
* Main.java
*
* @author chintan patel
*/
public class Main {
/*
* This method converts an int value to a String object.
*/
public void convertIntToString() {
int intToConvert = 50;
//One way of converting from int to String
String convertedValue = Integer.toString(intToConvert);
System.out.println(convertedValue + " : " + Integer.toString(intToConvert).getClass());
//Another way of converting from int to String
convertedValue = new Integer(intToConvert).toString();
System.out.println(convertedValue + " : " + new Integer(intToConvert).toString().getClass());
//A third way of converting from int to String
convertedValue = "" + intToConvert;
System.out.println(convertedValue + " : " + ("" + intToConvert).getClass());
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertIntToString();
}
}

Convert String to byte

This example shows how to convert a String to a byte.
The String can only contain digits (or start with the - sign) and the number has to be within the byte range, otherwise a NumberFormatException will be thrown.
The output from the code below is:
65
Tried to convert an invalid value
 
 
/**
*
* @author chintan patel
*/
public class Main {
/**
* Example method for converting a String to a byte
*/
public void convertStringToByte() {
try {
String s = "65";
byte b = Byte.valueOf(s);
System.out.println(b);
//Causes a NumberFormatException since the value is out of range
System.out.println(Byte.valueOf("129"));
} catch (NumberFormatException ex) {
System.out.println("Tried to convert an invalid value");
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertStringToByte();
}
}

Convert String to character array

This example shows how to do a String to character array conversion. The String class has a neat method for doing this, toCharArray().
In the code example below the String is converted to a char array and each element of the array is printed out.
 
 
/**
* Main.java
*
* @author chitnan patel
*/
public class Main {
/**
* Converts a String to a character array
*/
public void convertStringToCharArray() {
String str = "Abcdefg";
char[] cArray = str.toCharArray();
for (char c : cArray)
System.out.println(c);
}
/**
* Starts the program
*
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertStringToCharArray();
}
}
The output from the executed code:
 
A
b
c
d
e
f
g

Character array to String conversion

This java code example shows how to convert an array of characters to a String.
To accomplish this we can utilize one of the String class many contructors, which takes an array of characters as parameter.
 
/**
* Main.java
*
* @author chintan patel
*/
public class Main {
/**
* Converts an array of characters to a String
*/
public void convertCharArrayToString() {
char[] charArray = new char[] {'a', 'b', 'c'};
String str = new String(charArray);
System.out.println(str);
}
/**
* Starts the program
*
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertCharArrayToString();
}
}

Convert byte to String

This example shows three ways of converting a variable of datatype byte to a String.
The first example uses the wrapper class Byte and it's static method toString to convert the byte.
The second example just concatenates the byte with an empty String, and the value is automatically casted to a String.
The final example creates a byte array which is passed to the constructor of the String class.
The output of the code below is:
65
65
A
 
 
 
/**
*
* @author chintan patel
*/
public class Main {
/**
* Example method for converting a byte to a String.
*/
public void convertByteToString() {
byte b = 65;
//Using the static toString method of the Byte class
System.out.println(Byte.toString(b));
//Using simple concatenation with an empty String
System.out.println(b + "");
//Creating a byte array and passing it to the String constructor
System.out.println(new String(new byte[] {b}));
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertByteToString();
}
}

Convert Boolean to String

To convert a boolean value to a String you need to use the wrapper class of the boolean datatype.
It has the same name as the datatype boolean, but it begins with the captial B - Boolean.
To convert a boolean value you create an instance of the wrapper class sending the boolean value as argument to the constructor.
Then you simply call the toString() method which will return a String representation of the boolean value.
 
/**
* Main.java
*
* @author chintan patel
*/
public class Main {
/**
* Boolean to String conversion
*/
public void convertBooleanToString() {
boolean theValue = true;
//Do the boolean to String conversion
String theValueAsString = new Boolean(theValue).toString();
System.out.println(theValueAsString);
}
/**
* Starts the program
*
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertBooleanToString();
}
}

Convert String to Boolean

There's actually two ways to do a string to boolean conversion. Either you can create an instance of the wrapper class Boolean with a string value as argument to the constructor and call the method booleanValue(), or you can do as in the example below:
call the static method parseBoolean() of the wrapper class to convert the string value to a boolean.
Either way, the string value sent in has to be either 'true' or 'TRUE' to result in a boolean with the value of true, but it doesn't have to be 'false' to result in a false boolean value.
It actually makes sense that any other string value than 'true' or 'TRUE' will result in a return value that is set to false.
 
 
/**
* Main.java
*
* @author chintan patel
*/
public class Main {
/**
* String to boolean conversion
*/
public void convertStringToBoolean() {
String strBoolean = "true";
//Do the String to boolean conversion
boolean theValue = Boolean.parseBoolean(strBoolean);
System.out.println(theValue);
}
/**
* Starts the program
*
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertStringToBoolean();
}
}

Convert String to byte array

This little code example shows a String to byte array conversion.
The String class has a method called getBytes which returns an array of bytes.
In the example the length of the array is printed out to illustrate that the length of the array is the same as the number of characters in the String.
/**
*
* @author chintan patel
*/
public class Main {
/*
* This method converts a String to an array of bytes
*/
public void convertStringToByteArray() {
String stringToConvert = "This String is 76 characters long and will be converted to an array of bytes";
byte[] theByteArray = stringToConvert.getBytes();
System.out.println(theByteArray.length);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertStringToByteArray();
}
}

Convert byte[ ] array to String

Making a byte array to String conversion in Java is very simple since one of the String class constructors takes an array of bytes as argument.
We simply create the object with our array as argument to convert the byte array to a String, and then print out the value.
/*
* Main.java
*
* @author chintan patel
*/
public class Main {
/*
* This method converts an byte array to a String object.
*/
public void convertByteArrayToString() {
byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};
String value = new String(byteArray);
System.out.println(value);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertByteArrayToString();
}
}

Tuesday, May 26, 2009

How To Embeded Flash in Java Desktop App

Most of examples about playing Flash animation on desktop application I found on the internet to are done by VB. But today I found java version. Flash SWT Plugin, it work very well on my latest project :).

To use Flash SWT Plugin, download com.docuverse.swt.flash-0.4.zip and extract it somewhere on local disk. Now our eclipse flash project need to add atleast two external jars e.g. flash.jar[from where we just extract the zip] and swt.jar and now we are ready to code.

THE SOURCE
To play swf file, all we need is FlashPlayer object and activate it that all. it'll look like this.




import com.docuverse.swt.flash.FlashPlayer;

public class SWTPlayer {
....
private void run() {
// TODO Auto-generated method stub
Display display = new Display();
Shell shell = new Shell(display);
FlashPlayer player = new FlashPlayer(shell);
player.loadMovie(0, "yourflashfile.swf");
player.setSize(550, 400);
player.activate();
shell.setSize(550, 400);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}

How To: Test Your Antivirus

How To: Test Your Antivirus


Have you ever wondered if your anti virus is working properly? I haven’t had a virus alarm for a while now so I started doubting if my antivirus
was working properly or was just hogging my system memory and wasting my time download updates and definitions for nothing.So I decided to find a way to test it, but how could I test my antivirus without risking damaging my system? Why creating my own little virus of course.I’ll show you how to make a virus using notepad that will test the ability and efficiency of your current antivirus without causing any damage to your computer even if you don’t have an anti virus nothing will happen.Lets get to it:


1) Open a new notepad document

2) Type the code below into the notepad file.

X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*


3) Save the notepad file as FakeVirus.com or whatever you want, To comfortably find the file, I suggest placing it in the Desktop.To save a file in .com format all you need to do is change the “Save as type:” to All Files and then just enter FakeVirus.com in the “File name:” section and click Save.

4) Run the FakeVirus.com file to test your computers efficiency. If your anti virus software
doesn’t give you a warning or alert, I suggest changing your AntiVirus immediately as your current one doesn’t work properly.Check out this article for a few good free antivirus softwares.

5) After your done with the file just delete it and empty the trash, remember this fake virus won’t affect your computer in any way.

Enjoy.

Monday, May 25, 2009

Dos Commands

Let's take a look at some important DOS commands available in Windows XP. These commands/tools must be run from the command prompt of the cmd.exe command interpreter.

To run cmd.exe, click Start, click Run, type cmd and click OK. You will then see a black window similar to the one above.

Tip: Wherever you have to type the path to a folder after the command, just drag the file or folder from Windows Explorer into the command window instead of typing the whole path.

Assoc: Displays or modifies file name extension associations. Used without parameters, assoc displays a list of all the current file name extension associations.

At: Schedules commands and programs to run on a computer at a specified time and date. You can use at only when the Schedule service is running. Used without parameters, at lists scheduled commands.

Attrib: Displays, sets, or removes the read-only, archive, system, and hidden attributes assigned to files or directories. Used without parameters, attrib displays attributes of all files in the current directory.

Comp: Compares the contents of two files or sets of files byte by byte. Comp can compare files on the same drive or on different drives, and in the same directory or in different directories. When comp compares the files, it displays their locations and file names. Used without parameters, comp prompts you to enter the files to compare.

Copy: Copies one or more files from one location to another.

Cprofile: Cleans specified profiles of wasted space and, if user-specific file associations are disabled, removes these associations from the registry. Profiles that are currently in use are not modified.

Defrag: Locates and consolidates fragmented boot files, data files, and folders on local volumes.

Driverquery: Displays a list of all installed device drivers and their properties.

Fc: Compares two files and displays the differences between them. Fc can even resynchronize files if there is a mismatch.

Find: Searches for a specific string of text in a file or files. After searching the specified file or files, find displays any lines of text that contain the specified string.

Getmac: Returns the media access control (MAC) address and list of network protocols associated with each address for all network cards in each computer, either locally or across a network.

Help: Provides online information about system commands (that is, non-network commands). Used without parameters, help lists and briefly describes every system command.

Helpctr: Starts Help and Support Center. Used without parameters, helpctr displays the Help and Support Center home page.

Hostname: Displays the host name portion of the full computer name of the computer.

Ipconfig: Displays all current TCP/IP network configuration values and refreshes Dynamic Host Configuration Protocol (DHCP) and Domain Name System (DNS) settings. Used without parameters, ipconfig displays the IP address, subnet mask, and default gateway for all adapters.

Irftp: Sends files over an infrared link. Used without parameters or used with /s, irftp opens the Wireless Link dialog box, where you can select the files that you want to send without using the command line.

Lpq: Displays the status of a print queue on a computer running Line Printer Daemon (LPD). Used without parameters, lpq displays command-line help for the lpq command.

Mmc: Opens Microsoft Management Console (MMC). Using the mmc command-line options, you can open a specific MMC console, open MMC in author mode, or specify that the 32-bit or 64-bit version of MMC is opened.

More: Generally used along with other commands, displays one screen of output at a time.

Move: More convenient than copy-paste. Moves one or more files from one directory to the specified directory. For example, you have some Excel files having their names start with "MonthlyReport" in your My Documents folder which you want to move to a separate folder. Using the Windows XP Explorer, you would have to manually select every single file and then use cut-paste. Using the move command to perform the same task is much simpler and easier. Type the following command and hit enter:
move MonthlyReport*.xls c:\MonthlyReports\

Msinfo32: Displays a comprehensive view of your hardware, system components, and software environment.

Netstat: This command is very useful to diagnose slow internet connections. It displays active TCP connections, ports on which the computer is listening, Ethernet statistics, the IP routing table, IPv4 statistics (for the IP, ICMP, TCP, and UDP protocols), and IPv6 statistics (for the IPv6, ICMPv6, TCP over IPv6, and UDP over IPv6 protocols). Used without parameters, netstat displays active TCP connections.

Openfiles: Queries or displays open files. Also queries, displays, or disconnects files opened by network users.

Ping: Verifies IP-level connectivity to another TCP/IP computer by sending Internet Control Message Protocol (ICMP) Echo Request messages. The receipt of corresponding Echo Reply messages are displayed, along with round-trip times. Ping is the primary TCP/IP command used to troubleshoot connectivity, reachability, and name resolution. Used without parameters, ping displays help.

Recover: Recovers readable information from a bad or defective disk.

Runas: Allows a user to run specific tools and programs with different permissions than the user's current logon provides.

Shutdown: Allows you to shut down or restart a local or remote computer. Used without parameters, shutdown will logoff the current user.

Start: Starts a separate Command Prompt window to run a specified program or command. Used without parameters, start opens a second command prompt window.

Systeminfo: Displays detailed configuration information about a computer and its operating system, including operating system configuration, security information, product ID, and hardware properties, such as RAM, disk space, and network cards.

Taskkill: Ends one or more tasks or processes. Processes can be killed by process ID or image name.

Tasklist: Displays a list of applications and services with their Process ID (PID) for all tasks running on either a local or a remote computer.

Tree: Graphically displays the directory structure of a path or of the disk in a drive.

Ver: Displays the Windows XP version number.

Vol: Displays the disk volume label and serial number, if they exist. A serial number is displayed for a disk formatted with MS-DOS version 4.0 or later.

W32tm: A tool used to diagnose problems occurring with Windows Time.

Xcopy: Copies files and directories, including subdirectories.

You can find the complete list of command prompt commands for Windows XP, Syntax, Parameters & Examples here.