Reading files a la for-each loop.

January 27th, 2009

This post will show you how to use the for-each loop for reading files.  This approach tried to replace the following approach


    try {
        BufferedReader in = new BufferedReader(new FileReader("infilename"));
        String str;
        while ((str = in.readLine()) != null) {
            process(str);
        }
        in.close();
    } catch (IOException e) {
    }

with this one:


    final IterableFileReader e = new IterableFileReader(new File("SomeFile.WithSomeExtension"));
    for(String eachLine: e){
        process(eachLine);
    }

The source code of my solution is illustrated herein:


public class IterableFileReader implements Iterable<String>{
    private final BufferedReader reader;
    public IterableFileReader(InputStream is, Charset encoding) throws IOException {
        reader = new BufferedReader(new InputStreamReader(is, encoding.toString()));
    }

    public IterableFileReader(File file) throws IOException {
        this(new FileInputStream(file), Charset.UTF_8);
    }

    public Iterator<String> iterator() {
        return new Iterator<String>(){
            private String line;
            public boolean hasNext() {
                try {
                    line = reader.readLine();
                } catch (IOException e) {
                    throw new IllegalStateException(e);
                }
                return line != null;
            }

            public String next() {
                return line;
            }

            public void remove() {
                throw new UnsupportedOperationException("remove is not supported. sorry dude!");
            }
        };
    }
}

I hope you will find this approach useful. Ok, time is up. I gotta go, my daughter is crying. Till next time.

programming, toolset | Comments | Trackback

Leave a Reply

  1.  
  2.  
  3.  
  4. XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
  5. Spam Protection by WP-SpamFree

You can keep track of new comments to this post with the comments feed.

 

January 2009
M T W T F S S
« Oct   May »
 1234
567891011
12131415161718
19202122232425
262728293031  

Categories

Archives

Tags