Guys, how to retrieve a text file in java???

Member Avatar for ztini

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?

Member Avatar for ztini

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.