Skip to content

Method: close()

1: package de.fhdw.wtf.file;
2:
3: import java.io.BufferedReader;
4: import java.io.File;
5: import java.io.FileNotFoundException;
6: import java.io.FileReader;
7: import java.io.IOException;
8: import java.util.LinkedList;
9:
10: /**
11: * Iterator for {@link File}s. It reads the file line by line and returns the lines.
12: */
13: public class FileIterator implements AutoCloseable {
14:         
15:         /**
16:          * BufferedReader for reading the file.
17:          */
18:         private final BufferedReader reader;
19:         
20:         /**
21:          * List of lines of the file.
22:          */
23:         private final LinkedList<String> nextlines;
24:         
25:         /**
26:          * Constructor of {@link FileIterator}.
27:          *
28:          * @param file
29:          * file
30:          * @throws FileNotFoundException
31:          * possible Exceptions
32:          */
33:         public FileIterator(final File file) throws FileNotFoundException {
34:                 this.reader = new BufferedReader(new FileReader(file));
35:                 this.nextlines = new LinkedList<>();
36:         }
37:         
38:         @Override
39:         public void close() throws IOException {
40:                 this.reader.close();
41:         }
42:         
43:         /**
44:          * Returns <true> if the file has at least one more line.
45:          *
46:          * @return Boolean
47:          */
48:         public boolean hasNext() {
49:                 String next = null;
50:                 try {
51:                         next = this.reader.readLine();
52:                         if (next != null) {
53:                                 this.nextlines.addLast(next);
54:                         }
55:                 } catch (final IOException e) {
56:                         e.printStackTrace();
57:                 }
58:                 return !this.nextlines.isEmpty();
59:         }
60:         
61:         /**
62:          * Returns the next line of the file.
63:          *
64:          * @return next line
65:          */
66:         public String next() {
67:                 return this.nextlines.poll();
68:         }
69: }