Random blog

for randomness

Subscribe to RSS feed

HIM - SWRMXS (2010)

, , , ...

How HIM disappointed me once again awww

Read more...

Cities XL music

, , ,

Pretty good, take it for a spin.



Leave a comment.

Java: Read an internal text resource into String

, ,

Easy static method for reading text resources into Strings.

This works only if you place a text resource in the same package where the call is being made, for example:

my/domain/stuff/MyClass.class
my/domain/stuff/my_text_file.txt

The method goes like this (assuming there's an Utils class somewhere in your classes):

public static <T> String readTextFile(Class<T> clazz, String resourceName) throws IOException {
  	StringBuffer sb = new StringBuffer(1024);
	BufferedInputStream inStream = new BufferedInputStream(clazz.getResourceAsStream(resourceName));
  	byte[] chars = new byte[1024];
  	int bytesRead = 0;
  	while( (bytesRead = inStream.read(chars)) > -1){
  		//System.out.println(bytesRead);
  		sb.append(new String(chars, 0, bytesRead));
	}
  	inStream.close();
    	return sb.toString();
}


and you would make a call like this:

Utils.<MyClass>readTextFile(MyClass.class, "my_text_file.txt")


Parameterizing the method is quite important, it involves some ClassLoader magic, which I don't know much about and don't have the time to investigate.

So there you go. Do you find this useful?