设计模式-迭代器模式

设计简单的文件迭代器,从文件中依次读入每行的字符串。

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());
		}
	}
	
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值