Created
December 9, 2014 02:23
-
-
Save daichan4649/23afd1bea66b3fa091be to your computer and use it in GitHub Desktop.
JavaEE 環境でクラスパス配下のファイルを文字列として読み込む(JSON等)
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
// dir name(class pathをルートとする相対パス) | |
private static final String DIR_NAME = "json"; | |
private static final String FILE_NAME = "test.json"; | |
public static String createJsonText(Class<? extends HttpServlet> clazz) { | |
return createJsonText(clazz, DIR_NAME, FILE_NAME); | |
} | |
public static String createJsonText(Class<? extends HttpServlet> clazz, String dirName, String fileName) { | |
String dirPath = clazz.getClassLoader().getResource(dirName).getPath(); | |
return createJsonText(new File(dirPath, fileName)); | |
} | |
private static String createJsonText(File jsonFile) { | |
try { | |
byte[] bytes = Files.readAllBytes(Paths.get(jsonFile.toURI())); | |
return new String(bytes, StandardCharsets.UTF_8); | |
} catch (Exception e) { | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment