/**
 * 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

Recent Math PhD now doing a post-doctorate at UC Riverside.

Kuei-Nuan Lin