1、文件流
现在让我们看下这种解决方案——我们将使用java.util.Scanner类扫描文件的内容,一行一行连续地读取:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
FileInputStream inputStream
= null ; Scanner sc = null ; try { inputStream
= new FileInputStream(path); sc
= new Scanner(inputStream, "UTF-8" ); while (sc.hasNextLine())
{ String line
= sc.nextLine(); //
System.out.println(line); } //
note that Scanner suppresses exceptions if (sc.ioException()
!= null )
{ throw sc.ioException(); } } finally { if (inputStream
!= null )
{ inputStream.close(); } if (sc
!= null )
{ sc.close(); } } |
2、Apache Commons IO流
同样也可以使用Commons IO库实现,利用该库提供的自定义LineIterator:
1
2
3
4
5
6
7
8
9
|
LineIterator it = FileUtils. Iterator(theFile, "UTF-8" ); try { while (it.hasNext())
{ String
line = it.nextLine(); //
do something with line } } finally { LineIterator.closeQuietly(it); } |