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

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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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,现实文件行的读取

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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内容请搜索靠谱客的其他文章。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部