Revision as of 06:55, 4 December 2010 by Han84 (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
/**
 * Read string from the file.
 * @param fileName
 * @return
 */
public static String[] fileToStringArray(String fileName) {
	java.io.FileReader fr = null;
	try {
		fr = new java.io.FileReader(new java.io.File(fileName));
	} catch (java.io.FileNotFoundException ex) {
		Ts.printErr(ex);
	}
	java.io.BufferedReader br = new java.io.BufferedReader(fr);
	int counter = Ts.fileCountLines(fileName);
	String[] result = new String[counter];
	for (int i = 0; i < counter; i++) {
		try {
			result[i] = br.readLine();
		} catch (java.io.IOException ex) {
			Ts.printErr(ex);
		}
	}
	try {
		br.close();
		fr.close();
	} catch (java.io.IOException ex) {
		Ts.printErr(ex);
	}
	return result;
}
 
/**
 * Determine the number of text lines in a file.
 * @param fileName
 * @return
 */
public static int fileCountLines(String fileName) {
	int count = 0;
	java.io.FileReader fr = null;
	try {
		fr = new java.io.FileReader(new java.io.File(fileName));
	} catch (java.io.FileNotFoundException ex) {
		Ts.printErr(ex);
	}
	java.io.BufferedReader br = new java.io.BufferedReader(fr);
	try {
		while (br.readLine() != null) {
			count++;
		}
	} catch (java.io.IOException ex) {
		Ts.printErr(ex);
	}
	return count;
}
 
public static void printErr(java.lang.Exception ex) {
	printErr(ex.getMessage());
}


Back to JavaHowTo

Alumni Liaison

Ph.D. 2007, working on developing cool imaging technologies for digital cameras, camera phones, and video surveillance cameras.

Buyue Zhang