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 --------------------------------
No comments:
Post a Comment