自定义iterator 利用增强for循环实现文件行的读取
2013-02-13 17:24
871 查看
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); } } }
相关文章推荐
- 利用fscanf和fprintf实现文件读取和写入
- 利用java反射机制 读取配置文件 实现动态类加载以及动态类型转换
- 读取配置文件和自定义配置文件(python实现)
- Halcon中循环读取文件的实现以及数字与字符的转换
- 利用POI读取Excel数据,实现同时读取多个Excel文件,兼容所有浏览器
- Visual C++利用互斥量同步线程实现文件读取进度条
- Struts2 <s:iterator> 标签实现 for 循环式 循环控制
- Java中的增强for循环与iterator
- php利用SPL实现针对大文件的读取
- 如何利用C/C++逐行读取txt文件中的字符串(可以顺便实现文本文件的复制)
- 如何利用C/C++逐行读取txt文件中的字符串(可以顺便实现文本文件的复制)
- 利用for循环实现程序的延时
- Halcon中循环读取文件的实现以及数字与字符的转换
- android应用面试宝典(下);用自定义组件控制循环组件使用bug还添加标志显示答案标志位;通过包名读取配置文件AndroidManifest.xml
- 利用Apache的commons-net实现FTP的文件读取、上传、下载、删除和移动功能
- (18)servletContext应用:获取web应用的初始化参数、实现servlet转发、利用servletContext对象读取资源文件
- 利用JAVA/JSF/JSP实现读取并截取.txt文件http://zhidao.baidu.com/question/42189115.html
- 利用Shell脚本循环读取文件中每一行的方法详解
- Swift编程语言中如何实现自定义类型的for-in循环(基于Swift 2.2)
- jmeter从文件中读取参数,并实现循环