public void traverseFilesFolders () {
if (referencedFile.exists()) {
traverseFilesFolders(referencedFile);
} else {
System.out.println("File or Folder does not exist");
}
}
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.
Email the blog author at: nicholaskeytholeong [at] gmail [dot] com
Labels:
Algorithms,
General Knowledge,
Java,
Useful Method
Final vs Finally vs Finalize
A short note for myself:
Final: used for defining a class non-subclassable, and making a member variable as a
constant which cannot be modified, and declare a method non-overridable.
Finally: to provide the capability to execute code no matter whether or
not an exception is thrown or caught in the try-catch exception handler.
Finalize: helps in garbage collection to clean up objects that are no longer required. Usualy Java will do the garbage collection automatically.
Final: used for defining a class non-subclassable, and making a member variable as a
constant which cannot be modified, and declare a method non-overridable.
Finally: to provide the capability to execute code no matter whether or
not an exception is thrown or caught in the try-catch exception handler.
Finalize: helps in garbage collection to clean up objects that are no longer required. Usualy Java will do the garbage collection automatically.
Email the blog author at: nicholaskeytholeong [at] gmail [dot] com
Labels:
General Knowledge,
Java
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()
getInterfaces()
getName()
getClass()
getSuperclass()
getMethods()
getFields()
getConstructors()
The output of the code is as follow. Nothing fancy, nothing complicated. Everything is straightforward.
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();
}
}
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
Email the blog author at: nicholaskeytholeong [at] gmail [dot] com
Labels:
General Knowledge,
Java,
Useful Method
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()".
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".
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();
}
}
Email the blog author at: nicholaskeytholeong [at] gmail [dot] com
Labels:
Algorithms,
General Knowledge,
Java,
Useful Method
Thursday, October 8, 2009
MediaPlayer vs SoundPool
Here is my recommendation if you are not sure which class to use - MediaPlayer or SoundPool when developing an Android application.
MediaPlayer:
If you were to play a background music in your application, you should go for MediaPlayer. MediaPlayer is my preferred class because it allows you to playback a lengthy audio file.
SoundPool:
As the name explains itself, SoundPool class allows you to playback a collection of short sound effects quickly and it does not lag much. Imagine yourself writing a game with several sound effects meant for different actions. You may use a HashMap to compile the list of SFXs and then play it by accessing the index number (key in the HashMap).
Summary:
Notice the adjectives I used for different classes.
Lengthy, theme = MediaPlayer
Short, effect = SoundPool
MediaPlayer:
If you were to play a background music in your application, you should go for MediaPlayer. MediaPlayer is my preferred class because it allows you to playback a lengthy audio file.
SoundPool:
As the name explains itself, SoundPool class allows you to playback a collection of short sound effects quickly and it does not lag much. Imagine yourself writing a game with several sound effects meant for different actions. You may use a HashMap to compile the list of SFXs and then play it by accessing the index number (key in the HashMap).
Summary:
Notice the adjectives I used for different classes.
Lengthy, theme = MediaPlayer
Short, effect = SoundPool
Email the blog author at: nicholaskeytholeong [at] gmail [dot] com
Labels:
Android,
Java,
Technology
Monday, October 5, 2009
Reading XML in Android platform
I find these XmlResourceParser and XmlPullParser classes useful to read XML files when we are dealing with Android platform. Below is the code sample I use in my Android project:Here is an example from the Android Developers website.
Email the blog author at: nicholaskeytholeong [at] gmail [dot] com
Labels:
Android,
Java,
Technology,
XML
Detailed explanation of using XSL to scrape ISO country codes
I apologize if you couldn't understand how I managed to scrape the country codes from the ISO website as mentioned in my previous article. Here are the detailed steps to scrape the codes accordingly. You'll need 3 things to achieve the goal: manual editing (I know it's primitive otherwise you are more than welcomed to write your HTML tag stripper to recognize the elements in the web page), XML file and XSL file.
[1] Copy the table element:
- Copy the entire table element that contains the country names and codes
[2] Editing the XML file:
- Open an empty file
- Save it as "countries.xml"
- Add this line at the top of the XML file:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="countries.xsl"?>
- Paste the table element you copied earlier
- Remove the table row that contains "Country names" and "ISO 3166-1-alpha-2 code"
- The screenshot is as below:
[3] Editing the XSL file:
- Copy the XPath codes I demonstrated in this article
- Save it as "countries.xsl"
[4] You are all set!
- Here is the sample output translating the XML using XPath
[1] Copy the table element:
- Copy the entire table element that contains the country names and codes
[2] Editing the XML file:
- Open an empty file
- Save it as "countries.xml"
- Add this line at the top of the XML file:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="countries.xsl"?>
- Paste the table element you copied earlier
- Remove the table row that contains "Country names" and "ISO 3166-1-alpha-2 code"
- The screenshot is as below:
[3] Editing the XSL file:- Copy the XPath codes I demonstrated in this article
- Save it as "countries.xsl"
[4] You are all set!
- Here is the sample output translating the XML using XPath
Email the blog author at: nicholaskeytholeong [at] gmail [dot] com
Labels:
Country Codes,
General Knowledge,
ISO 3166-1-alpha-2,
Java,
XML,
XSL
Subscribe to:
Posts (Atom)