Паттерн: Итератор (Iterator)
Исходник: FileLineList.java, язык: java [code #500, hits: 7241]
автор: this [добавлен: 05.10.2007]
  1. package iterator;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.FileNotFoundException;
  7. import java.io.IOException;
  8. import java.io.InputStreamReader;
  9. import java.util.AbstractList;
  10.  
  11. public class FileLineList extends AbstractList<String> {
  12. protected BufferedReader reader;
  13. private File f;
  14.  
  15. public FileLineList(String filePath) throws FileNotFoundException {
  16. f = new File(filePath);
  17. if (!f.canRead()) {
  18. throw new FileNotFoundException("Файл '" + f.getAbsolutePath() + "' - не найден!");
  19. }
  20. }
  21.  
  22. public String get(int index) {
  23. try {
  24. Init();
  25. String line;
  26. int count = 0;
  27. while ((line = reader.readLine()) != null) {
  28. if (index == count++) {
  29. return line;
  30. }
  31. }
  32. reader.close();
  33. } catch (IOException e) {
  34. WriteReadingError();
  35. }
  36. return null;
  37. }
  38.  
  39. public int size() {
  40. int count = 0;
  41. try {
  42. Init();
  43. while (reader.readLine() != null) count++;
  44. reader.close();
  45. } catch (IOException e) {
  46. WriteReadingError();
  47. }
  48. return count;
  49. }
  50.  
  51. protected void Init() throws IOException {
  52. reader = new BufferedReader(
  53. )
  54. );
  55. }
  56.  
  57. protected void WriteReadingError() {
  58. System.out.println("Ошибка чтения файла: " + f.getAbsolutePath() + "!");
  59. }
  60. }
  61.  
Сущность Concretelterator

Реализация итератора построчного обращения к файлу.
Тестировалось на: java 1.5.0_04

+добавить реализацию