×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: Boulty Doolin
Added: Sep 28, 2017 2:21 PM
Modified: Sep 28, 2017 2:23 PM
Views: 7
Read the entire contents of a text file into a string.
  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.util.Scanner;
  4.  
  5. public class TempWrapper {
  6.  
  7.     /**
  8.      * Gets the contents of a text file as a string. Note - only suitable for reasonably sized text files otherwise
  9.      * you will run into memory problems.
  10.      * @param filename The name of the file to read from.
  11.      * @return The contents of the file.
  12.      * @throws FileNotFoundException
  13.      */
  14.     public String getTextFileContents(String filename) throws FileNotFoundException {
  15.         Scanner scanner = null;
  16.         String content = null;
  17.         try {
  18.             File file = new File(filename);
  19.             scanner = new Scanner(file, "UTF-8");
  20.             scanner.useDelimiter("\\Z");
  21.             content = scanner.next();
  22.         } finally {
  23.             if (scanner != null) {
  24.                 scanner.close();
  25.             }
  26.         }
  27.         return content;
  28.     }
  29.  
  30. }
  31.