Created
July 16, 2014 08:18
-
-
Save aarondai/c8d173116ec4dd31be56 to your computer and use it in GitHub Desktop.
Java: Read File Into String
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
| String readFile(String fileName) throws IOException { | |
| BufferedReader br = new BufferedReader(new FileReader(fileName)); | |
| try { | |
| StringBuilder sb = new StringBuilder(); | |
| String line = br.readLine(); | |
| while (line != null) { | |
| sb.append(line); | |
| sb.append("\n"); | |
| line = br.readLine(); | |
| } | |
| return sb.toString(); | |
| } finally { | |
| br.close(); | |
| } | |
| } |
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
| try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) { | |
| StringBuilder sb = new StringBuilder(); | |
| String line = br.readLine(); | |
| while (line != null) { | |
| sb.append(line); | |
| sb.append(System.lineSeparator()); | |
| line = br.readLine(); | |
| } | |
| String everything = sb.toString(); | |
| } |
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
| FileInputStream inputStream = new FileInputStream("foo.txt"); | |
| try { | |
| String everything = IOUtils.toString(inputStream); | |
| } finally { | |
| inputStream.close(); | |
| } |
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
| try(FileInputStream inputStream = new FileInputStream("foo.txt")) { | |
| Session IOUtils; | |
| String everything = IOUtils.toString(inputStream); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment