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