设计简单的文件迭代器,从文件中依次读入每行的字符串。
package com.mapbar.tools;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
/**
*
* Class FileIterator.java
*
* Description 文件迭代器
*
* Company mapbar
*
* author Chenll E-mail: Chenll@mapbar.com
*
* Version 1.0
*
* Date 2011-8-2 下午05:36:40
*/
public class FileIterator implements Iterator<String> {
//文件
protected File file;
//编码
protected String codeset;
//读取器
protected BufferedReader reader;
//每行数据
protected String item;
//读取的总行数
protected int lineNumber;
//是否关闭
protected boolean closed = false;
/**
* 构造器
* @param path 文件路径
* @param code 编码
*/
public FileIterator(String path, String code) {
if (path == null || path.trim().length() == 0)
throw new IllegalArgumentException("file name is null");
try {
this.file = new File(path);
this.codeset = code;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 构造器
* @param file 文件
* @param code 编码
*/
public FileIterator(File file, String code) {
this.file = file;
this.codeset = code;
}
public File getFile() {
return file;
}
public String getCodeSet() {
return codeset;
}
public boolean hasNext() {
if (closed)
return false;
if (item != null){
return true;
}
tryNext();
return (!closed && item != null);
}
/**
* 读取下一行
*/
private void tryNext() {
try {
if (lineNumber == 0) {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream(file), codeset));
}
if (reader != null) {
item = reader.readLine();
if (item == null) {
close();
} else {
lineNumber++;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 取出下一行数据
*/
public String next() {
if (!hasNext())
throw new IllegalStateException();
String last = item;
item = null;
return last;
}
public int getLineNumber() {
return lineNumber;
}
public String getLine() {
return item;
}
/**
* 迭代器关闭
*/
public void close() {
closed = true;
if (reader != null){
try {
reader.close();
} catch (Exception ce) {
ce.printStackTrace();
} finally {
reader = null;
}
}
}
@Override
public void remove() {
// TODO Auto-generated method stub
}
public static void main(String[] args){
String path = "D:\\files\\1.txt";
for(FileIterator iterator=new FileIterator(path,"GBK");iterator.hasNext();){
System.out.println(iterator.next());
}
}
}