GetFileAsStringFrom WikiJavabuy this book
The name of the file to read is passed in input as a String. IOException is thrown in case of any problem in reading the file.
the articlegetFileAsString instances a import java.io.BufferedReader to efficiently read the data from the file. BufferedReader reads text from a character-input stream, buffering characters to provide efficient reading of characters, arrays, and lines. The java.lang.StringBuffer is basically the same thing as a java.lang.String with the exception that it's mutable and it's methods are thread safe. At the end of the processing the BufferedReader stream is closed. getFileAsStringimport java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; ... private final static String NEWLINE = System.getProperty("line.separator"); /** * * reads a the content of a file and returns is as a String * * @param filename the filename to read * @return the String containing the text of the file * @throws IOException */ public static String getFileAsString(String filename) throws IOException { try { BufferedReader bufferedReader = new BufferedReader(new FileReader(filename)); StringBuffer stringBuffer = new StringBuffer(); String line; while ((line = bufferedReader.readLine()) != null) { stringBuffer.append(line); stringBuffer.append(NEWLINE); } bufferedReader.close(); return stringBuffer.toString(); } catch (IOException e) { throw new IOException ("unable to read from file: "+ filename ); } }
|
