Skip to content

Instantly share code, notes, and snippets.

@oliverdaff
Created September 20, 2011 03:47
Show Gist options
  • Save oliverdaff/1228278 to your computer and use it in GitHub Desktop.
Save oliverdaff/1228278 to your computer and use it in GitHub Desktop.
FileLoader to load from classpath or filepath like Spring
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URISyntaxException;
public class FileLoader {
private static final String CLASSPATH_CONST = "classpath:";
private static final String FILEPATH_CONST = "filepath:";
public File loadFile(String file) throws FileNotFoundException{
try {
File fileToParse = getFile(file);
if(!fileToParse.exists()){
throw new FileNotFoundException();
}
return fileToParse;
} catch (URISyntaxException e) {
throw new FileNotFoundException();
}
}
/**
* The returned object of this method should be checked for existance
* @return a file object
* @throws URISyntaxException
*/
public File getFile(String file) throws URISyntaxException{
if(file.startsWith(CLASSPATH_CONST)){
return new File(
this.getClass().getResource(file.substring(CLASSPATH_CONST.length())).toURI());
} else if(file.startsWith(FILEPATH_CONST)){
return new File(file.substring(FILEPATH_CONST.length()));
} else {
return new File(file);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment