Created
December 24, 2018 15:23
-
-
Save ramiresnas/b3a2e1556a4e908c340fdee2a6344332 to your computer and use it in GitHub Desktop.
Reader file from resource folder when use maven.
This file contains hidden or 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
| /** | |
| * This code snippet help you read file content from resorce folder. | |
| * When you use the maven, the method: | |
| * | |
| * this.getClass().getResource(fileName) | |
| * | |
| * Don't work, so to resolve this problem, we use the this.getClass().getResourceAsStream(fileName) | |
| * and we read all content of file. This code snippet was only tested with text content, ex: file.txt, person.json and so on. | |
| */ | |
| private String getFileContent(String fileName) throws IOException { | |
| InputStream resource = null; | |
| InputStreamReader reader = null; | |
| BufferedReader bufferedReader = null; | |
| StringBuilder lines = new StringBuilder(); | |
| try { | |
| resource = this.getClass().getResourceAsStream(fileName); | |
| reader = new InputStreamReader(resource); | |
| bufferedReader = new BufferedReader(reader); | |
| String str; | |
| while ((str = bufferedReader.readLine()) != null) { | |
| lines.append(str); | |
| } | |
| } catch (Exception e) { | |
| e.printStackTrace(); | |
| }finally { | |
| resource.close(); | |
| reader.close(); | |
| bufferedReader.close(); | |
| } | |
| return lines.toString(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment