Created
October 2, 2011 08:21
-
-
Save ukyo/1257228 to your computer and use it in GitHub Desktop.
a simple file reader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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