View Javadoc

1   /*
2    * Copyright 2004 Piotr Maj
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package pl.kernelpanic.dbmonster.util;
17  
18  import java.io.BufferedReader;
19  import java.io.File;
20  import java.io.FileReader;
21  import java.io.LineNumberReader;
22  import java.io.Reader;
23  import java.io.StringReader;
24  import java.util.Iterator;
25  
26  
27  /***
28   * @author Piotr Maj <ant@kernelpanic.pl>
29   *
30   * @version $Revision: 1.1 $ $Date: 2007/06/21 08:38:14 $
31   */
32  public class ScriptReaderIterator implements Iterator {
33  
34      private LineNumberReader reader;
35      private String nextLine;
36  
37      public ScriptReaderIterator(String script) {
38          this.reader = new LineNumberReader(new StringReader(script));
39          prepareNextLine();
40      }
41  
42      public ScriptReaderIterator(Reader reader) {
43          this.reader = new LineNumberReader(new BufferedReader(reader));
44          prepareNextLine();
45      }
46  
47      public ScriptReaderIterator(File file) throws Exception {
48          this.reader = new LineNumberReader(new BufferedReader(new FileReader(file)));
49          prepareNextLine();
50      }
51  
52      public void remove() {
53      }
54  
55      public boolean hasNext() {
56          return nextLine != null;
57      }
58  
59      public Object next() {
60          String s = nextLine;
61          prepareNextLine();
62          return s;
63      }
64  
65      private void prepareNextLine() {
66          try {
67              nextLine = reader.readLine();
68              if (nextLine != null) {
69                  if ("".equals(nextLine.trim())) {
70                      prepareNextLine();
71                  }
72              }
73          } catch (Exception e) {
74              System.err.println("Could not read line: " + e.getMessage());
75          }
76      }
77  }