Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- public class IterFileWrapper implements Iterable <String> {
- private File file;
- public IterFileWrapper(String fileName) throws IOException {
- this(new File(fileName));
- }
- public IterFileWrapper(File file) throws IOException {
- if(!file.exists())
- throw new FileNotFoundException( "File does not exist");
- if(!file.isFile())
- throw new IOException( "File is not of type 'file'");
- else {
- this.file = file;
- }
- }
- public IterFileWrapperIterator iterator(){
- try {
- return new IterFileWrapperIterator(file);
- } catch( IOException e ) {
- e.printStackTrace();
- return null;
- }
- }
- }
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileReader;
- import java.io.IOException;
- import java.util.Iterator;
- import java.util.NoSuchElementException;
- public class IterFileWrapperIterator implements Iterator<String> {
- private FileReader reader;
- private BufferedReader in = null;
- private String string = null;
- public IterFileWrapperIterator(File file) throws IOException {
- try {
- reader = new FileReader(file);
- in = new BufferedReader(reader);
- string = in.readLine();
- if( string == null ) {
- in.close();
- }
- }
- catch( IOException ex ) {
- ex.printStackTrace();
- }
- }
- @Override
- public boolean hasNext() {
- return string != null;
- }
- @Override
- public String next() throws NoSuchElementException {
- String returnString = string;
- try {
- if( string == null ) {
- throw new NoSuchElementException( "Next line is not available" );
- }
- else {
- string = in.readLine();
- }
- }
- catch( Exception ex )
- {
- throw new NoSuchElementException();
- }
- return returnString;
- }
- }
- import java.io.IOException;
- public class IterFile {
- public static void main(String[] args) throws IOException {
- String filename = "src/IterFile.txt";
- for (String s : new IterFileWrapper(filename))
- System.out.println(s);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement