Saturday, December 27, 2008

How do I retrieve the System Properties on Windows Machine using Java

There are different ways to get the System properties of a System or Machine using Java Program. 
The following code first create a file called SystemProperties.xml and then retrieves all the System Property using Java's own function called getProperties() of Properties class and finally dumps it to the the created XML File.

SystemProperties.java
--------------------------------------------
import java.util.Properties;
import java.io.PrintStream;
import java.io.File;

/*
  File   : SystemProperties.java
  Purpose: Dumps all the System Properties and values to a XML file
  Author : Anaparthi Subrahmanyam 
  Published: 2008-12-27
  Usage Notification: Author doesnt own responsibility of any loss of data, responsibility for misuse or loss of any nature if this      code is used. If possible, please provide link to this webpage
*/

public class SystemProperties 
{
  public static void main(String[] args) 
  {
    try
    {
       File f = new File("SystemProperties.xml");
       //if creating a file called SystemProperties.xml, if returns false, exception will be thrown
       if(!f.createNewFile())
       {
          throw new Exception("Exception encoutered may be due to the file already exist.");
       }
       Properties prop = System.getProperties();
       // opening file in print stream so that later this stream will be used to write 
       PrintStream pst = new PrintStream(f.getName());
       // Passing three parameters to the storeToXML.
       //1. printstream
       //2. Comment to the XML File 
       //3. encoding format
       prop.storeToXML(pst,"System Properties details", "UTF-8");
       System.out.println("Sucessfully dumped the System Details to the file: " +f.getName());
    }
    catch (Exception e)
    {
      System.out.println("Error: "+e.getMessage());
    }
   }
}
-----------------------
Please provide your comments.

If you like this content please provide a link of this page on your page.


No comments:

Post a Comment