Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, June 25, 2008

Resource Loader

Following method can be used to load a resource file :-



package mypackage.loader;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class FileLoader
{
public static void main(String[] args) throws Exception
{
InputStream is = FileLoader.getFileAsStream("test.txt");
int size = is.available();
byte[] b = new byte[size];
is.read(b);

System.out.println(new String(b));
}

/**
* Searches a file in the following order :-

* Current package

* Classpath

* System classpath

* Current directory


* In case the file name is an absolute path to the file, it will be loaded
* from that location only.
* @param fileName
* @return InputStream for the loaded file.
* @throws FileNotFoundException If file not found in any of the listed location.
*/
public static InputStream getFileAsStream(String fileName) throws FileNotFoundException
{
InputStream is = null;

// First find the Class of the caller.
String callerClassName = new Exception().getStackTrace()[1].getClassName();

try
{
Class callerClass = Class.forName(callerClassName);

// First search the file in the current package
is = callerClass.getResourceAsStream(fileName);
}
catch (ClassNotFoundException e)
{
; // Ignore
}

// If not found in the callers package then check in classpath
if(is == null)
{
ClassLoader cl = FileLoader.class.getClassLoader();
is = cl.getResourceAsStream(fileName);

// If not check in system classpath
if(is == null)
{
ClassLoader scl = ClassLoader.getSystemClassLoader();
is = scl.getResourceAsStream(fileName);

// Finally check in current directory.
// Again if the file name is fully qualified file name then this part
// will be used to load the file.
if(is == null)
{
is = new FileInputStream(fileName);
}
}
}

return is;
}
}





------------------------- END OF CODE --------------------------------

Thursday, December 6, 2007

Java LinkedList vs ArrayList

Which one is better ArrayList or LinkedList ?

An ArrayList is a List implementation backed by a Java array, similar to the Vector class. As the number of elements in the collection increases, the internal array grows to fit them. If there are lots of growth periods, performance degrades as the old array needs to be copied into the new array. However, random access is very quick as it uses an array index to access.

With a LinkedList, the List implementation is backed by a doubly linked list data structure, allowing easy inserts/deletions anywhere in the structure, but really slow random accesses as the access must start at an end to get to the specific position.

Which one should you use really depends on the type of operations you need to support.

Source: http://www.jguru.com/faq/view.jsp?EID=106663