Showing posts with label Useful Method. Show all posts
Showing posts with label Useful Method. Show all posts

Wednesday, October 21, 2009

Traversing Folder and Files

Here is an updated code to inform you if the file or folder specified does not exists. You may take a look at the original code at this article.


public void traverseFilesFolders () {
if (referencedFile.exists()) {
traverseFilesFolders(referencedFile);
} else {
System.out.println("File or Folder does not exist");
}
}

Monday, October 19, 2009

Java Reflection

The Reflection API allows the user to get the complete, but not limited to, information about classes, constructors, interfaces and methods that are being used. There are many things we can achieve with this API and the methods are:
getInterfaces()
getName()
getClass()
getSuperclass()
getMethods()
getFields()
getConstructors()

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectionTool {

private static final String padding = "\t";

public void retrieveInterfaces(){
System.out.println("Retrieve Interface(s):");
for (Class anInterface: java.util.Date.class.getInterfaces()) {
System.out.println(padding + anInterface);
}
}

public void retrieveName(){
System.out.println("Retrieve Name of Class:");
System.out.println(padding + java.util.concurrent.atomic.AtomicInteger.class.getName());
}

public void retrieveClass(){
System.out.println("Retrieve Runtime Class:");
System.out.println(padding + java.util.zip.CRC32.class.getClass());
}

public void retrieveSuperClass(){
System.out.println("Retrieve Superclass:");
System.out.println(padding + java.util.zip.CRC32.class.getClass().getSuperclass());
}

public void retrieveMethods(){
System.out.println("Retrieve Methods:");
for (Method aMethod: java.util.List.class.getMethods()) {
System.out.println(padding + aMethod);
}
}

public void retrieveFields(){
System.out.println("Retrieve Fields:");
for (Field aField: java.lang.Double.class.getFields()) {
System.out.println(padding + aField);
}
}

public void retrieveConstructors(){
System.out.println("Retrieve Constructors:");
for (Constructor aConstructor: java.lang.Double.class.getConstructors()) {
System.out.println(padding + aConstructor);
}
}

public static void main(String[] args) {
ReflectionTool rt = new ReflectionTool();
rt.retrieveInterfaces();
rt.retrieveName();
rt.retrieveClass();
rt.retrieveSuperClass();
rt.retrieveMethods();
rt.retrieveFields();
rt.retrieveConstructors();
}
}

The output of the code is as follow. Nothing fancy, nothing complicated. Everything is straightforward.

Retrieve Interface(s):
interface java.io.Serializable
interface java.lang.Cloneable
interface java.lang.Comparable
Retrieve Name of Class:
java.util.concurrent.atomic.AtomicInteger
Retrieve Runtime Class:
class java.lang.Class
Retrieve Superclass:
class java.lang.Object
Retrieve Methods:
public abstract int java.util.List.hashCode()
public abstract boolean java.util.List.equals(java.lang.Object)
public abstract java.lang.Object java.util.List.get(int)
public abstract boolean java.util.List.add(java.lang.Object)
public abstract void java.util.List.add(int,java.lang.Object)
public abstract int java.util.List.indexOf(java.lang.Object)
public abstract void java.util.List.clear()
public abstract int java.util.List.lastIndexOf(java.lang.Object)
public abstract boolean java.util.List.contains(java.lang.Object)
public abstract boolean java.util.List.addAll(java.util.Collection)
public abstract boolean java.util.List.addAll(int,java.util.Collection)
public abstract int java.util.List.size()
public abstract java.lang.Object[] java.util.List.toArray()
public abstract java.lang.Object[] java.util.List.toArray(java.lang.Object[])
public abstract java.util.Iterator java.util.List.iterator()
public abstract java.lang.Object java.util.List.set(int,java.lang.Object)
public abstract boolean java.util.List.remove(java.lang.Object)
public abstract java.lang.Object java.util.List.remove(int)
public abstract boolean java.util.List.isEmpty()
public abstract boolean java.util.List.containsAll(java.util.Collection)
public abstract boolean java.util.List.removeAll(java.util.Collection)
public abstract boolean java.util.List.retainAll(java.util.Collection)
public abstract java.util.List java.util.List.subList(int,int)
public abstract java.util.ListIterator java.util.List.listIterator()
public abstract java.util.ListIterator java.util.List.listIterator(int)
Retrieve Fields:
public static final double java.lang.Double.POSITIVE_INFINITY
public static final double java.lang.Double.NEGATIVE_INFINITY
public static final double java.lang.Double.NaN
public static final double java.lang.Double.MAX_VALUE
public static final double java.lang.Double.MIN_VALUE
public static final int java.lang.Double.SIZE
public static final java.lang.Class java.lang.Double.TYPE
Retrieve Constructors:
public java.lang.Double(double)
public java.lang.Double(java.lang.String) throws java.lang.NumberFormatException


Friday, October 16, 2009

Traversing Folders and Files Recursively

Both files and folders are represented as File object in the java.io package. We are recognizing if an object is a file by using the method "isFile()" and a folder with the method "isDirectory()".

import java.io.File;

public class FilesFoldersTraversal {

private final char SEPARATOR = File.separatorChar;
private File originalFile;
private File referencedFile;
private String pad = null;
private String absolutePathOriginalFile = null;

public FilesFoldersTraversal(String inputFileString) {
File inputFile = new File(inputFileString);
originalFile = inputFile;
referencedFile = inputFile;
absolutePathOriginalFile = originalFile.getAbsolutePath();
}

public void traverseFilesFolders () {
traverseFilesFolders(referencedFile);
}

private void traverseFilesFolders(File referencedFile){
if (referencedFile.isDirectory()){
pad = getPadding(referencedFile);
processFolders(referencedFile);
}
else if (referencedFile.isFile()){
processFiles(referencedFile);
}
}

private void processFolders(File referencedFile){
System.out.println(pad + "Folder: " + referencedFile.getName());
File listFiles[] = referencedFile.listFiles();
for(File singleFile : listFiles){
traverseFilesFolders(singleFile);
}
}

private void processFiles(File referencedFile){
System.out.println(pad + " " + "File: " + referencedFile.getName());
}

private String getPadding(File referencedFile){
String padding = "";
String fileAbsolutePath = referencedFile.getAbsolutePath();
String filePathSubString = fileAbsolutePath.substring(absolutePathOriginalFile.length(), fileAbsolutePath.length());

int index = 0;
int subStringLength = filePathSubString.length();
while (index < subStringLength) {
if (filePathSubString.charAt(index) == SEPARATOR){
padding += " ";
}
index++;
}

return padding;
}

public static void main(String[] args) {
FilesFoldersTraversal fft = new FilesFoldersTraversal("/Users/YOUR_USER_NAME/Documents");
fft.traverseFilesFolders();
}

}
There are many interesting things you can do with the example shown. You may add a few lines of codes to compile a list of files of a specific file extension, for example ".txt" or ".class".

Tuesday, September 1, 2009

Fibonacci Sequence

Here's an interesting usage of "memoization". According to Wikipedia, "In computing, memoization is an optimization technique used primarily to speed up computer programs by having function calls avoid repeating the calculation of results for previously-processed inputs.".

There is actually a drawback if we are using plain and simple recursion to compute the Fibonacci sequence using long datatype (because we are only limited to hold the first 48 Fibonacci numbers). Memoization helps to speed up the computation time by saving already computed values into memory (and we can use BigInteger datatype). An example implementation is as below:

import java.math.BigInteger;
import java.util.ArrayList;

public class Fibonacci {

/** Variables for memoization **/
private static ArrayList fibMemoized = new ArrayList();
static {
fibMemoized.add(BigInteger.ZERO);
fibMemoized.add(BigInteger.ONE);
}

/** Memoized method to retrieve stored computed values **/
public static BigInteger fibonacci(int n) {
if (n >= fibMemoized.size()) {
fibMemoized.add(n, fibonacci(n-1).add(fibonacci(n-2)));
}
return fibMemoized.get(n);
}

/** Old school recursion **/
public static long fib(int n) {
if (n <= 1) return n;
else return fib(n-1) + fib(n-2);
}

/** Driver **/
public static void main(String[] args) {
int N = 45;
System.out.println(fibonacci(N));
System.out.println(fib(N));
}

}
You may try copying the codes and run it locally to observe the difference in performance. The typical recursive method runs slower because it computes the Fibonnaci numbers from scratch many times. Unlike the memoized method, the ArrayList is used to store the previously computed values. While memoized method is more superior in terms of speed, we are actually sacrificing space in order to achieve greater speed.

Wednesday, July 29, 2009

Sorting a vector of objects using Comparator

Here is something really cool about sorting a Vector of objects. At least it is appealing to me. Let say we have a vector of "Students" objects and we are interested to sort the objects using one of its private fields, say, "StudentID" which is of data type Integer.

The code is as follow:

public static void anyMethod(){
try {
Collections.sort(yourVectorThatContainsObjects, ComparatorName);
} catch (Exception ex) {}
}

public static Comparator<Object> ComparatorName = new Comparator<Object>() {
public int compare(Object resultItem1, Object resultItem2) {
Integer id1 = ((Students)resultItem1).StudentID;
Integer id2 = ((Students)resultItem2).StudentID;
return id2.compareTo(id1);
}
};
The result of this sort is in descending order, eg largest to smallest. However there is a simple trick to sort it in an ascending order. Simply use "return id1.compareTo(id2);" It works for me. I hope it works for you too. Otherwise, please feel free to leave a comment so that I can investigate my code :)