我們先來看個例子
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
|
import java.io.*; /** * Created by liguoqing on 2016/3/28. */ public class ReadTxtFile { public static void readTxt(String filePath) { try { File file = new File(filePath); if (file.isFile() && file.exists()) { InputStreamReader isr = new InputStreamReader( new FileInputStream(file), "utf-8" ); BufferedReader br = new BufferedReader(isr); String lineTxt = null ; while ((lineTxt = br.readLine()) != null ) { System.out.println(lineTxt); } br.close(); } else { System.out.println( "文件不存在!" ); } } catch (Exception e) { System.out.println( "文件讀取錯誤!" ); } } public static void main(String[] args) { String filePath = "D:\\test\\我.txt" ; readTxt(filePath); } } |
看完上面的例子,我們再來詳細研究下
java讀取txt文件內容。可以作如下理解:
首先獲得一個文件句柄。File file = new File(); file即為文件句柄。兩人之間連通電話網絡了。接下來可以開始打電話了。
通過這條線路讀取甲方的信息:new FileInputStream(file) 目前這個信息已經讀進來內存當中了。接下來需要解讀成乙方可以理解的東西
既然你使用了FileInputStream()。那么對應的需要使用InputStreamReader()這個方法進行解讀剛才裝進來內存當中的數據
解讀完成后要輸出呀。那當然要轉換成IO可以識別的數據呀。那就需要調用字節碼讀取的方法BufferedReader()。同時使用bufferedReader()的readline()方法讀取txt文件中的每一行數據哈。
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
|
package com.campu; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.Reader; /** * @author 碼農小江 * H20121012.java * 2012-10-12下午11:40:21 */ public class H20121012 { /** * 功能:Java讀取txt文件的內容 * 步驟:1:先獲得文件句柄 * 2:獲得文件句柄當做是輸入一個字節碼流,需要對這個輸入流進行讀取 * 3:讀取到輸入流后,需要讀取生成字節流 * 4:一行一行的輸出。readline()。 * 備注:需要考慮的是異常情況 * @param filePath */ public static void readTxtFile(String filePath){ try { String encoding= "GBK" ; File file= new File(filePath); if (file.isFile() && file.exists()){ //判斷文件是否存在 InputStreamReader read = new InputStreamReader( new FileInputStream(file),encoding); //考慮到編碼格式 BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null ; while ((lineTxt = bufferedReader.readLine()) != null ){ System.out.println(lineTxt); } read.close(); } else { System.out.println( "找不到指定的文件" ); } } catch (Exception e) { System.out.println( "讀取文件內容出錯" ); e.printStackTrace(); } } public static void main(String argv[]){ String filePath = "L:\\Apache\\htdocs\\res\\20121012.txt" ; // "res/"; readTxtFile(filePath); } } |