Friday, 14th October 2011
Follow WikiJava on twitter now. @Wikijava

GetFileAsString

From WikiJava

Jump to: navigation, search
The author suggests:

buy this book


getFileAsString is a method that reads the content of a text file and returns it as a java.lang.String.

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.

Contents

the article

getFileAsString 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.

getFileAsString

import 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 );
	}
    }


Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page


Comments on wikijava are disabled now, cause excessive spam.