001 package gate.creole.morph;
002
003 import gate.util.BomStrippingInputStreamReader;
004
005 import java.io.*;
006 import java.net.URL;
007 import java.util.ArrayList;
008
009 /**
010 * <p>Title: ReadFile.java </p>
011 * <p>Description: This class provides methods to read the file (provided by the
012 * user) and to have the read access to each and every line separately </p>
013 */
014 public class ReadFile {
015
016 /** Instance of BufferedReader used to read the files with UTF-8 encoding */
017 private BufferedReader br;
018
019 /** Pointer which keeps track of what line is accessible to the user */
020 private int pointer = 0;
021
022 /** Stores each line of the file as a separate String in the ArrayList */
023 private ArrayList data;
024
025 /**
026 * Constructor - Initialise the buffered Reader instance
027 * @param fileName Name of the file to be read
028 */
029 public ReadFile(URL fileURL) {
030
031 data = new ArrayList();
032
033 try {
034 br = new BomStrippingInputStreamReader(fileURL.openStream(),
035 "UTF-8");
036 } catch(FileNotFoundException e) {
037 e.printStackTrace();
038 } catch(IOException e) {
039 e.printStackTrace();
040 }
041 }
042
043 /**
044 * Reads the file and stores each line as a separate element in the ArrayList
045 * @return true if read operation is successful, false otherwise
046 */
047 public boolean read() {
048 String text;
049 try {
050 text = br.readLine();
051 while(text!=null) {
052 data.add(text);
053 text = br.readLine();
054 }
055 text = null;
056 // file has been read, close it
057 br.close();
058 // now set the pointer to 0
059 pointer = 0;
060
061 } catch(IOException ie) {
062 ie.printStackTrace();
063 return false;
064 }
065 return true;
066 }
067
068 /**
069 * This method tells if next line is available to read
070 * @return true if line is available, false otherwise
071 */
072 public boolean hasNext() {
073 if(data.size()>pointer) {
074 return true;
075 } else {
076 return false;
077 }
078 }
079
080
081 /**
082 * This method gives the next available String (line from the file)
083 * @return line if available, null otherwise
084 */
085 public String getNext() {
086 if(data.size()>pointer) {
087 String value = (String)(data.get(pointer));
088 pointer++;
089 return value;
090 } else {
091 return null;
092 }
093 }
094
095 /**
096 * Tells the position of the pointer in the file
097 * @return line number where the pointer is located in the file
098 */
099 public int getPointer() {
100 return pointer;
101 }
102
103 }
|