我是靠谱客的博主 激昂云朵,最近开发中收集的这篇文章主要介绍自定义iterator 利用增强for循环实现文件行的读取,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

为什么80%的码农都做不了架构师?>>>   hot3.png

package cn.niki.fordemo;

import java.util.Iterator;

//这个类提供了文本文件的包装器,在遍历它的时候,它可以列出文件中的每一行

public class TextFile implements Iterable<String> {

    private String filename;
	public TextFile(String filename) {
		this.filename = filename;
	}
	// one method of the Iterable interface
	@Override
	public Iterator<String> iterator() {
		return new TextFileIterator(filename);
	}
	
}

自定义Iterator,现实文件行的读取

package cn.niki.fordemo;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

public class TextFileIterator implements Iterator<String> {

	// stream being read from
	BufferedReader in;
	// return value of next call to next()
	String nextline;

	// the structure method of TextFileItrator
	public TextFileIterator(String filename) {
		// 打开文件并读取第一行 如果第一行存在获得第一行
		try {
			in = new BufferedReader(new FileReader(filename));
			nextline = in.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// if the next line is non-null then we have a next line
	@Override
	public boolean hasNext() {
		return nextline != null;
	}

	// return the next line,but first read the line that follows it
	@Override
	public String next() {
		try {
			String result = nextline;
			//if we dont have reached EOF yet
			if (nextline != null) {
				nextline = in.readLine(); // read another line
				if (nextline == null)
					in.close(); // and close on EOF
			}
			return result;
		} catch (IOException e) {
		  throw new IllegalArgumentException(e);
		}
	}
   // we dont need remove the line just read it
	@Override
	public void remove() {
		throw new UnsupportedOperationException();
	}
	
	public static void main(String[] args){
		String filename="C://mail.txt";
	    //使用增强for循环进行文件的读取
	    for(String line:new TextFile(filename)){
	    	System.err.println(line);
	    }
	
	}
}

转载于:https://my.oschina.net/hsm/blog/108551

最后

以上就是激昂云朵为你收集整理的自定义iterator 利用增强for循环实现文件行的读取的全部内容,希望文章能够帮你解决自定义iterator 利用增强for循环实现文件行的读取所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(80)

评论列表共有 0 条评论

立即
投稿
返回
顶部