Posted on Jan 27, 2009

Reading files a la for-each loop.

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.

Posted on Jan 27, 2009

Still alive….

I am still here, with less time than ever, but still here. I will start blogging again very soon.