Advertisement
Guest User

Untitled

a guest
Jun 25th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.io.IOException;
  4.  
  5. public class IterFileWrapper implements Iterable <String> {
  6.  
  7. private File file;
  8.  
  9. public IterFileWrapper(String fileName) throws IOException {
  10. this(new File(fileName));
  11. }
  12.  
  13. public IterFileWrapper(File file) throws IOException {
  14. if(!file.exists())
  15. throw new FileNotFoundException( "File does not exist");
  16. if(!file.isFile())
  17. throw new IOException( "File is not of type 'file'");
  18. else {
  19. this.file = file;
  20. }
  21. }
  22.  
  23. public IterFileWrapperIterator iterator(){
  24. try {
  25. return new IterFileWrapperIterator(file);
  26. } catch( IOException e ) {
  27. e.printStackTrace();
  28. return null;
  29. }
  30. }
  31.  
  32. }
  33.  
  34. import java.io.BufferedReader;
  35. import java.io.File;
  36. import java.io.FileReader;
  37. import java.io.IOException;
  38. import java.util.Iterator;
  39. import java.util.NoSuchElementException;
  40.  
  41. public class IterFileWrapperIterator implements Iterator<String> {
  42. private FileReader reader;
  43. private BufferedReader in = null;
  44. private String string = null;
  45.  
  46. public IterFileWrapperIterator(File file) throws IOException {
  47. try {
  48. reader = new FileReader(file);
  49. in = new BufferedReader(reader);
  50. string = in.readLine();
  51. if( string == null ) {
  52. in.close();
  53. }
  54. }
  55. catch( IOException ex ) {
  56. ex.printStackTrace();
  57. }
  58. }
  59.  
  60. @Override
  61. public boolean hasNext() {
  62. return string != null;
  63. }
  64.  
  65. @Override
  66. public String next() throws NoSuchElementException {
  67. String returnString = string;
  68. try {
  69. if( string == null ) {
  70. throw new NoSuchElementException( "Next line is not available" );
  71. }
  72. else {
  73. string = in.readLine();
  74. }
  75. }
  76. catch( Exception ex )
  77. {
  78. throw new NoSuchElementException();
  79. }
  80. return returnString;
  81. }
  82. }
  83.  
  84. import java.io.IOException;
  85.  
  86. public class IterFile {
  87.  
  88. public static void main(String[] args) throws IOException {
  89.  
  90. String filename = "src/IterFile.txt";
  91.  
  92. for (String s : new IterFileWrapper(filename))
  93. System.out.println(s);
  94.  
  95. }
  96.  
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement