Skip to content

Instantly share code, notes, and snippets.

@ukyo
Created October 2, 2011 08:21
Show Gist options
  • Save ukyo/1257228 to your computer and use it in GitHub Desktop.
Save ukyo/1257228 to your computer and use it in GitHub Desktop.
a simple file reader
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
public class BufferedFileReader {
private static BufferedFileReader opener = new BufferedFileReader();
private BufferedFileReader() { }
public static File open(String filename) {
return open(filename, "UTF-8");
}
public static File open(String filename, String encoding) {
return opener.new File(filename, encoding);
}
private class File implements Iterable<String> {
private BufferedReader reader;
private String line = null;
private boolean callHasNext = false;
public File(String filename, String encoding) {
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(filename), encoding));
} catch (UnsupportedEncodingException e) {
} catch (FileNotFoundException e) { }
}
@Override
public Iterator<String> iterator() {
return new Iterator<String>() {
@Override
public void remove() { }
@Override
public String next() {
if (callHasNext) {
callHasNext = false;
return line;
}
try {
return reader.readLine();
} catch (IOException e) {
try {
reader.close();
} catch (IOException e1) { }
return null;
}
}
@Override
public boolean hasNext() {
try {
if (callHasNext) {
return true;
}
line = reader.readLine();
if (line == null) {
reader.close();
return false;
}
callHasNext = true;
return true;
} catch (IOException e) { }
return false;
}
};
}
}
/**
* @param args
*/
public static void main(String[] args) {
//Example
for(String line: BufferedFileReader.open("hoge.html", "euc_jp")) {
System.out.println(line);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment