1   package gate.creole.morph;
2   
3   import java.io.*;
4   import java.net.URL;
5   import java.util.ArrayList;
6   
7   /**
8    * <p>Title: ReadFile.java </p>
9    * <p>Description: This class provides methods to read the file (provided by the
10   * user) and to have the read access to each and every line separately </p>
11   */
12  public class ReadFile {
13  
14    /** Instance of BufferedReader used to read the files with UTF-8 encoding */
15    private BufferedReader br;
16  
17    /** Pointer which keeps track of what line is accessible to the user */
18    private int pointer = 0;
19  
20    /** Stores each line of the file as a separate String in the ArrayList */
21    private ArrayList data;
22  
23    /**
24     * Constructor - Initialise the buffered Reader instance
25     * @param fileName Name of the file to be read
26     */
27    public ReadFile(URL fileURL) {
28  
29      data = new ArrayList();
30  
31      try {
32        br = new BufferedReader(new InputStreamReader(fileURL.openStream(),
33                "UTF-8"));
34      } catch(FileNotFoundException e) {
35        e.printStackTrace();
36      } catch(IOException e) {
37        e.printStackTrace();
38      }
39    }
40  
41    /**
42     * Reads the file and stores each line as a separate element in the ArrayList
43     * @return true if read operation is successful, false otherwise
44     */
45    public boolean read() {
46      String text;
47      try {
48        text = br.readLine();
49        while(text!=null) {
50          data.add(text);
51          text = br.readLine();
52        }
53  
54        // file has been read, close it
55        br.close();
56  
57        // now set the pointer to 0
58        pointer = 0;
59  
60      } catch(IOException ie) {
61        ie.printStackTrace();
62        return false;
63      }
64      return true;
65    }
66  
67    /**
68     * This method tells if next line is available to read
69     * @return true if line is available, false otherwise
70     */
71    public boolean hasNext() {
72      if(data.size()>pointer) {
73        return true;
74      } else {
75        return false;
76      }
77    }
78  
79  
80    /**
81     * This method gives the next available String (line from the file)
82     * @return line if available, null otherwise
83     */
84    public String getNext() {
85      if(data.size()>pointer) {
86        String value = (String)(data.get(pointer));
87        pointer++;
88        return value;
89      } else {
90        return null;
91      }
92    }
93  
94    /**
95     * Tells the position of the pointer in the file
96     * @return line number where the pointer is located in the file
97     */
98    public int getPointer() {
99      return pointer;
100   }
101 
102 }