Get String From File

Instantiate a Java String from the contents in a Text file.

Javadoc available at https://www.javatapas.com/docs/javatapas/io/GetStringFromFile.html


public static String getStringFromFile(String fileName) throws IOException {

	StringBuffer sb = new StringBuffer();
	BufferedReader reader = new BufferedReader(new FileReader(fileName));

	String line = reader.readLine();

	while(line != null){
		sb.append(line);
		line = reader.readLine();
	}

	return sb.toString();
}

public static String getStringFromFile(String fileName, int bufferSize) throws IOException {

	StringBuffer sb = new StringBuffer();
	BufferedReader reader = new BufferedReader(new FileReader(fileName));

	char[] buf = new char[bufferSize];
	int numRead = 0;
	String readData;

	while ((numRead = reader.read(buf)) != -1) {
		sb.append(buf, 0, numRead);
	}

	return sb.toString();
}