Java: Reading and writing text files

A lot of people starting off with Java will often want to read or write text files. Here’s some code to do just that:

public static String readFile(String fileName) throws IOException {
	FileInputStream fis = new FileInputStream(fileName);
	BufferedInputStream bis = new BufferedInputStream(fis, 1024);
	byte[] buffer = new byte[1024];
	String result = "";
	int len;
	while ((len = != -1) {
		byte[] tmp = new byte[len];
		System.arraycopy(buffer, 0, tmp, 0, len);
		result += new String(tmp);
	return result;

public static void writeFile(String fileName, String content)
		throws IOException {
	FileOutputStream fos = new FileOutputStream(fileName);
	BufferedOutputStream bos = new BufferedOutputStream(fos, 1024);

Read More