//返回文件迭代器的工具类。
//文件名称:FileUtil.java
package com.cn;
import java.io.*;
import java.util.*;
public class FileUtil
{
public static Iterable<String> readlines(String filename) //返回用于对文件进行迭代的迭代器的静态方法
throws IOException
{
final FileReader fr = new FileReader(filename);
final BufferedReader br = new BufferedReader(fr);
return new Iterable<String>() {
public Iterator<String> iterator() {
return new Iterator<String>() { //返回文件迭代器,实现迭代接口。
public boolean hasNext() { //判断下一行是否为空。
return line != null;
}
public String next() { //返回当前行,同时读取文件的下一行作为当前行。
String retval = line;
line = getLine();
return retval;
}
public void remove() {
throw new UnsupportedOperationException();
}
String getLine() {
String line = null;
try {
line = br.readLine();
}
catch (IOException ioEx) {
line = null;
}
return line;
}
String line = getLine(); //读取文件的第一行作为当前行。
};
}
};
}
}
//测试类。DumpApp.java
package com.cn;
// FileUtils.java
//DumpApp.java
public class DumpApp
{
public static void main(String[] args)
throws Exception
{
for (String line : FileUtil.readlines("C://Documents and Settings//cw//My Documents//sample.txt"))
System.out.println(line);
}
}