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 = bis.read(buffer)) != -1) {
		byte[] tmp = new byte[len];
		System.arraycopy(buffer, 0, tmp, 0, len);
		result += new String(tmp);
	}
	bis.close();
	return result;
}

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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.