Jan 02

The Properties class has a store() method for saving a set of properties to a stream. There are lots of examples on the web that show how to use store() but unfortunately the majority of them fail to close the stream which is a bit misleading for new developers. Closing the stream is the responsibility of the caller (as mentioned in the javadoc), and failure to do it can result in the properties not being written to their ultimate destination.

Here’s an example showing how to write the properties to a file (including closing the stream).

Properties prop = new Properties();
OutputStream out = new FileOutputStream("my.properties"); 
try {
     prop.setProperty("abc", "123");
     prop.store(out, null);
} catch (IOException ex) {
     ex.printStackTrace();
} finally {
     out.close();
}

written by objects \\ tags: , , ,

Jul 18

Check the system property “sun.arch.data.model”

System.out.println(System.getProperty("sun.arch.data.model"));

written by objects \\ tags: , , , ,

Oct 01

Say you have a class with a number of properties, and you then have a Collection of these beans and you want to find the bean with the smallest value of one of the properties.

Instead of using a loop to go through the collection to find the smallest element based on our condition we can instead use the Collections.min() method. You just need to pass it the collection to search for the minimum and a Comparator that defines how two beans should be compared.


MyBean max = Collections.min(collectionOfMyBean, 
   new Comparator< MyBean >() {
      public int compare(MyBean bean1, MyBean beans2) {

           // We'll assume for the sake of this example 
           // that the bean property is Comparable.
           // If its not then you would just need to 
           // adjust how the 2 values are compared

           return bean1.getProperty().compareTo(bean2.getProperty());
       }
    });

written by objects \\ tags: , , , , ,