Created
September 20, 2011 03:47
-
-
Save oliverdaff/1228278 to your computer and use it in GitHub Desktop.
FileLoader to load from classpath or filepath like Spring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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