Hi Vin, I like to use a static utility class like this:

import java.io.BufferedReader;
import java.io.FileReader;


public class Utility {
	public static BufferedReader openFile(String filename) {
		try {
			return new BufferedReader(new FileReader(filename));
		}
		catch (Exception e)	{
			return null;
		}
	}
	
	public static void closeFile(BufferedReader reader) {
		try {
			reader.close();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static String readLine(BufferedReader reader) {
		try {
			return reader.readLine();
		}
		catch (Exception e) {
			return null;
		}
	}
}

Hi ztini.
May you explain what is the point of using the static methods.
is it only to avoid using the try-catch?

Edited 5 Years Ago by naief: n/a

Hi naeif, sorry I missed your question.

Compare the two:

BufferedReader br = Utility.openFile("somefile.txt");

or,

Utility utility = new Utility()
BufferedReader br = utility.openFile("somefile.txt");

There's no real difference; just preference.

Not sure what you mean by "[avoiding] try-catch". Each method utilizes try-catch. Unless you mean, changing the method calls to throw an exception, like this:

public static BufferedReader openFile(String filename) throws IOException

At which point, you would need to surround Utility.openFile(file) with a try/catch. Why force your user to implement try/catch; just do it yourself. But again, all preference.

This question has already been answered. Start a new discussion instead.