package textfile; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /* * Created on Apr 28, 2004 * Originally created for CSE142-04sp Assignment 4 (Movie Data Base) */ /** A buffered reader for text files with fields delimited by some * regular expression * (for example, by a TAB character). * @author dickey */ public class DelimitedTextReader extends BufferedReader { /**tab character is the default delimiter. */ public static final String DEFAULT_DELIMITER = "/t"; private String delimiter = DEFAULT_DELIMITER; /** Create a reader with the default delimiter. * @param in a reader; same assumptions as for the constuctor of * BufferedReader. */ public DelimitedTextReader(Reader in) { super(in); } /** Create a reader with an arbitrary string as delimiter. * * @param in a reader; same assumptions as for the constuctor of * BufferedReader. * @param delimiter a regular expression defining the string used to * separate fields on each line. Although this can be any regular * expression in principle, it is expected that it will normally be * something simple, like a single character. */ public DelimitedTextReader(Reader in, final String delimiter) { this(in); this.delimiter = delimiter; } /** Create a reader with the default delimiter. * @param in see BufferedReader * @param sz see BufferedReader */ public DelimitedTextReader(Reader in, int sz) { super(in, sz); } /** Create a reader with an arbitrary string as delimiter. * @param in see BufferedReader * @param sz see BufferedReader * @param delimiter see DelimitedTextReader(in, delimiter). */ public DelimitedTextReader(Reader in, int sz, String delimiter) { this(in, sz); this.delimiter = delimiter; } /** Read the next line of the file and give it back as a list of * Strings. The strings in the list were separated on the original * line by the delimiter string. * @return a list containing all the fields of the line, or null if * end of file has been reached. * @throws IOException */ public ArrayList readLineAsFieldList() throws IOException { String[] fields = readLineAsFieldArray(); if (fields == null) { return null; } List flist = Arrays.asList(fields); ArrayList alist = new ArrayList(flist); return alist; } /** Read the next line of the file and give it back as an array of * Strings. The strings in the array were separated on the original * line by the delimiter string. * @return an array containing all the fields of the line, or null if * end of file has been reached. * @throws IOException */ public String[] readLineAsFieldArray()throws IOException { String thisLine = this.readLine(); if (thisLine == null) { //end of file has been reached return null; } //split as many times as possible around the delimiter String[] fields = thisLine.split(this.delimiter, -1); return fields; } }