Wednesday, April 20, 2011

How to get file from filename

Recently I had a issue regarding how to read a file, as in eclipse environment and actually server environment, the relative directory is different, it caused a lot of problem, below it is a example which works for both environment.

File file ;
URL url = this.getClass().getClassLoader().getResource(fileName);

try {
file = new File(url.toURI());
} catch(URISyntaxException e) {
file = new File(url.getPath());
}

or to a string

URL loadedResource = this.getClass().getClassLoader().getResource(fileName);


InputStream inputStream = loadedResource.openStream();

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
return sb.toString();

No comments:

Post a Comment